简体   繁体   中英

How can I get an instance of non-named inner class by Java reflection?

A sample code written as bellow:

interface DisplayListener {
    public void display();
}

class Outer {
    public void prepare() {
        register(new DisplayLitener() {
            public void display() { /* do something */ }
        });
    }

    public void print() {
        // TODO: print all instances of DisplayerListener
    }
}

I tried to one way using getFields() and getDeclaredFields(). No expected result found.

Any body can find a way to make an execution marked by TODO by Java reflection?

Thanks so much.

When you write

new DisplayListener() {
  public void display() {
    ...
  }
}

you are declaring a new anonymous inner class which implements DisplayListener and also create an instance of it. So reflection will not help you in this case. The statement above simply creates a normal java object that you can save in a list as follows:

public class Outer {

  List<DisplayListener> list = new ArrayList<>();

  public void prepare() {
    register(new DisplayListener() {
      @Override
      public void display() { /* do something */ }
    });
  }

  void register(DisplayListener displayListener) {
    list.add(displayListener);
  }

  public void print() {
    System.out.println(list);
  }

  public static void main(String[] args) {
    Outer o = new Outer();
    o.prepare();
    o.prepare();
    o.print();
  }
}

This example prints "[Outer$1@5ca881b5, Outer$1@24d46ca6]". The class Outer$1 denotes the anonymous inner class and we have 2 instances in the list. "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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