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
.
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
.
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.