Get a reference to a class object of an anonymous inner class

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

With a non-anonymous class, this is done using ClassName.class.

+4
source share
1 answer

If you request a reference to an anonymous class to reference an anonymous class, the instance object java.lang.Classfor your anonymous class is how you can do this.

If you assign an instance of an anonymous class to a variable obj, you can have a reference to class c obj.getClass(). The example uses Object, but any class finaland any interface can be used .

Object obj = new Object() {

};

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

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

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
}

"" ( , ), .

+6

All Articles