44

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?

Jen S.
  • 4,106
  • 4
  • 35
  • 44

3 Answers3

67

Class.getDeclaredClasses() is the answer.

azro
  • 53,056
  • 7
  • 34
  • 70
Jen S.
  • 4,106
  • 4
  • 35
  • 44
5

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

Cogsy
  • 5,584
  • 4
  • 35
  • 47
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);
        }

}
Radiodef
  • 37,180
  • 14
  • 90
  • 125
Shrirang
  • 67
  • 1
  • 1