我可以使用反射发现 Java 类声明的内部类吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/471749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:03:39  来源:igfitidea点击:

Can I discover a Java class' declared inner classes using reflection?

javareflection

提问by Jen S.

In Java, is there any way to use the JDK libraries to discover the private classes implemented within another class? Or do I need so use something like asm?

在 Java 中,有没有办法使用 JDK 库来发现在另一个类中实现的私有类?或者我需要使用像asm这样的东西吗?

采纳答案by Jen S.

回答by Cogsy

I think this is what you're after: Class.getClasses().

我认为这就是你所追求的:课堂。getClasses()

回答by Shrirang

package com.test;

public class A {

    public String str;

    public class B {
        private int i;
    }
}
package com.test;

import junit.framework.TestCase;

public class ReflectAB extends TestCase {
    public void testAccessToOuterClass() throws Exception {
           final A a = new A();
           final A.B b = a.new B();
           final Class[] parent = A.class.getClasses();
           assertEquals("com.test.A$B", parent[0].getName());
           assertEquals("i" , parent[0].getDeclaredFields()[0].getName());
           assertEquals("int",parent[0].getDeclaredFields()[0].getType().getName());
           //assertSame(a, a2);
        }

}