Jen S.
Jen S.

Reputation: 4234

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

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?

Upvotes: 46

Views: 30215

Answers (3)

Cogsy
Cogsy

Reputation: 5642

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

Upvotes: 4

Jen S.
Jen S.

Reputation: 4234

Class.getDeclaredClasses() is the answer.

Upvotes: 71

Shrirang
Shrirang

Reputation: 65

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

}

Upvotes: 4

Related Questions