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?
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.
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.
You can access the private methods of a class using java reflection package.
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.
Class.getDeclaredClasses()
is the answer.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With