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?
Asked
Active
Viewed 2.8k times
3 Answers
67
Class.getDeclaredClasses()
is the answer.
-
3Sadly, this doesn't list anonymous inner classes (javap will report them). – Caesar Apr 16 '20 at 00:19
5
I think this is what you're after: Class.getClasses().

Cogsy
- 5,584
- 4
- 35
- 47
-
No it's not, `getClasses()` returns public classes only, including inherited ones. – andbi Aug 05 '22 at 21:17
5
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);
}
}