gpt4 book ai didi

java - 获取实例的声明类 : possible?

转载 作者:行者123 更新时间:2023-11-30 09:09:08 29 4
gpt4 key购买 nike

有没有办法在运行时检索实例的声明类?例如:

public class Caller {
private JFrame frame = new JFrame("Test");
private JButton button = new JButton("Test me");
private Callee callee = new Callee();

public Caller() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);

button.addActionListener(callee.getListener());

frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
new Caller();
}
}

被调用者:

public class Callee {
public ActionListener getListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/* Get the class "Caller" here and invoke its methods */
/* Something along the lines of: */
Object button = e.getSource();
button.getOwnerClass(); //This would return the type Caller
}
};
}
}

“getOwnerClass()”是一个虚构的方法。有没有办法得到类似的结果?

最佳答案

标准 API 中没有任何内容可让您获取此信息。有点不清楚“声明类”或“所有者类”是什么意思,但是为了这个答案,我假设它是其代码创建对象实例的类(您希望所有者类来自) .

默认情况下,JVM 不存储此信息。

但是,使用 the heap profiler that is packaged along with the JDK distribution ,您可以记录对象分配点的堆栈跟踪,并且可以在各个时间点将此信息写入文件。

这仍然没有为您提供检索信息的 API 调用,但它表明记录此类信息在技术上是可行的。

我在 Google 上搜索了一下,发现确实有人创建了一个 API,它使用与堆分析器(java.lang.instrumentation 包/JVMTI 接口(interface))相同的基本技术

通过一些工作,您应该能够用它构建一些东西。

该网站有一个很好的例子:

AllocationRecorder.addSampler(new Sampler() {
public void sampleAllocation(int count, String desc, Object newObj, long size) {
System.out.println("I just allocated the object " + newObj +
" of type " + desc + " whose size is " + size);
if (count != -1) { System.out.println("It's an array of size " + count); }
}
});

您应该使用 new Exception().getStackTrace() 获取堆栈跟踪,而不是打印,删除前几个引用采样器和 API 的 StackTraceElement 对象类,然后调用 StackTraceElement.getClassName() 以获取创建对象实例的类的名称,换句话说,就是您的 OwnerClass。

关于java - 获取实例的声明类 : possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23184403/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com