简体   繁体   English

如何使用反射动态获取调用者实例的实例

[英]How can I get the instance of the caller instance dynamically using reflection

I am working in a Swing application. 我正在使用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.
   }
}

I want some way to get the instance of the calling class instance, maybe using reflection. 我想要某种方法来获取调用类实例的实例,也许使用反射。 So that I can associate a KeyListener to each instance. 这样我就可以将KeyListener关联到每个实例。 This is required, otherwise I have to write the same codes in all the 1000 classes. 这是必需的,否则我必须在所有1000个类中编写相同的代码。

All my classes are extending JPanel , I can get the parent from the Parent property once the component is associated to the component to the parent. 我所有的类都在扩展JPanel ,一旦组件与组件关联到父级,就可以从Parent属性获取父级。 But here I need it inside the constructor of Child , ie the component is not associated to Owner yet. 但是在这里,我需要在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.
    }
 }

Something like that may help you: 这样的事情可能会帮助您:

public class Owner extends JPanel {
    Child child;

    public Owner() {
        child = new Child(this);
    }
}

public class Child extends JPanel {
    Owner owner;

    public Child(Owner owner) {
        this.owner = owner;
        // add key listeners here to owner
        owner.addKeyListener(...)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM