【发布时间】:2014-04-20 15:49:42
【问题描述】:
有没有办法在运行时检索实例的声明类? 例如:
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()”是一个虚构的方法。有没有办法得到类似的结果?
【问题讨论】:
-
对“Callee”的引用可以存储在多个位置,“Caller”没什么特别的 => Anwser 没有。
-
你的意思是
Caller.class? -
那会给你什么?您可以始终如一地使用这些信息做什么?您可以通过堆栈跟踪获得它。
-
@SotiriosDelimanolis 假设被调用者的 ActionListener 被多个类使用,所有这些类共享一个方法(由接口实现)。
-
你不能对所有的 Java 做出这样的假设。所以如此具体的东西是不可能存在的。您可以访问堆栈跟踪并获取堆栈上的类型,但您永远不知道堆栈要走多远。
标签: java class reflection instance