本文介绍了如何获得封闭课程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Class.getDeclaredClasses()可以获取它声明但不包含匿名类的所有类。

I know Class.getDeclaredClasses() can obtains all the classes that it has declared but doesn't including anonymous classes.

我想知道有没有办法通过封闭类获取所有封闭的类?例如,我想获得在 Root 中定义的所有封闭类以用于测试目的。

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() 
   }
}

预期结果是: [任务类]

推荐答案

如果您知道匿名类的命名方案,可以尝试使用 Root ClassLoader :

If you know the naming scheme of your anonymous classes, you can try to load it with Root's ClassLoader:

javac的命名方案是< enclosing_class_name> $< anonymous_class_number>

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");
}

这篇关于如何获得封闭课程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 23:05