我正在使用 Swing 应用程序。
public class Owner extends JPanel{
Child child=null;
public Owner(){
child=new Child();
}
}
public class Child extends JPanel{
public Child(){
// Here I want the instance of Owner class.
// This child class is being created from many classes(almost 1000) like the Owner class.
}
}
我想要某种方法来获取调用类实例的实例,也许使用反射。
这样我就可以将 KeyListener
与每个实例关联起来。
这是必需的,否则我必须在所有 1000 个类中编写相同的代码。
我的所有类都扩展了JPanel
,一旦组件与父组件关联,我就可以从Parent
属性获取父组件。但在这里我需要它在 Child
的构造函数中,即该组件尚未与 Owner
关联。
最佳答案
public class Owner extends JPanel{
Child child=null;
public Owner(){
child=new Child(this);
}
}
public class Child extends JPanel{
Object owner ;
public Child(Object owner ){
this.owner = owner ;
// Here I want the instance of Owner class.
// This child class is being created from many classes(almost 1000) like the Owner class.
}
}
关于java - 如何使用反射动态获取调用者实例的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11951802/