How to get enclosed class? [duplicate]

陌路散爱 提交于 2020-01-01 13:28:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!