问题
I know Class.getDeclaredClasses() can obtains all the classes that it has declared but doesn't including anonymous classes.
I'd like to know is there a way to get all the enclosed classes via the enclosing class ? for example, I want to get the all enclosed classes defined in Root for test purpose.
class Root{
void run(){
Runnable task = new Runnable(){
public void run(){}
};
task.getClass().getEnclosingClass();// return Root.class
// but I want to get all enclosed class via Root.class, for example:
// Root.class... == task.getClass()
}
}
the expected result is : [class of task].
回答1:
If you know the naming scheme of your anonymous classes, you can try to load it with Root's ClassLoader:
Naming scheme for javac is <enclosing_class_name>$<anonymous_class_number>:
Class<?> enclosing = Root.class;
try{
Class<?> anon1 = enclosing.getClassLoader().loadClass(enclosing.getName() + "$1");
System.out.println(anon1); // prints: class Root$1
} catch (ClassNotFoundException e) {
System.out.println("no anonymous classes");
}
来源:https://stackoverflow.com/questions/44475201/how-to-get-enclosed-class