4

How do you get the reference to the class object of an anonymous inner class in Java?

With non-anonimous class it is done with ClassName.class.

Nick Volynkin
  • 14,023
  • 6
  • 43
  • 67
LMK
  • 2,882
  • 5
  • 28
  • 52
  • 1
    What's a reference of an anonymous class? (You mean a reference to the `Class` object representing the anonymous class?) – aioobe Jun 16 '15 at 11:05
  • Cane be used by `.this` – Estimate Jun 16 '15 at 11:06
  • Please read carefully, the OP does not want a reference *to* the outer class but *in* the outer class. – Marvin Jun 16 '15 at 11:07
  • Aren't anonymous classes interfaces implemented inline? Like Interface i = new Interface() { //class impl goes here}; therefore you already have a reference when you create them. – uylmz Jun 16 '15 at 11:15
  • I bet this was a part of some conversation. Put out of the context it's very unclear what he wanted from you. – zubergu Jun 16 '15 at 11:27

1 Answers1

6

If for reference to the anonymous you ask a reference to the anonymous class, the java.lang.Class instance object to your anonymous class here is how you can do that.

If you assign the anonimous class instance to the variable obj you can have a reference to the class with obj.getClass(). The example uses Object, but any non-final class and any interface can be used.

Object obj = new Object() {

};

obj.getClass(); // Reference to the anonymous class

You can do the same also without explicitly creating a variable like obj for example

Button b = ...;
b.addActionListener(new ActionListener() {
    ....
}); 

ActionListener[] listeners = b.getActionListeners();
for (ActionListener listener : listeners) {
    System.out.println(listener.getClass());  // Prints the reference to the class
}

If no reference to the an object of type 'Anonymous' can be used (at least with reflection) you can't do that.

Nick Volynkin
  • 14,023
  • 6
  • 43
  • 67
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56