Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 627
Jen S. Avatar asked Jan 23 '09 03:01

Jen S.


People also ask

How do you access private inner class with reflection?

Accessing the Private Members Write an inner class in it, return the private members from a method within the inner class, say, getValue(), and finally from another class (from which you want to access the private members) call the getValue() method of the inner class.

How do you find the instance of a class using reflection?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.

Can we access private methods using reflection?

You can access the private methods of a class using java reflection package.

Does Java support reflection?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.


2 Answers

Class.getDeclaredClasses() is the answer.

like image 103
Jen S. Avatar answered Sep 21 '22 21:09

Jen S.


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);         }  } 
like image 24
Shrirang Avatar answered Sep 21 '22 21:09

Shrirang