Reflection example - accessing private data
by , 05-21-2011 at 05:28 PM (3152 Views)
If you think that you cannot access private data members of a class from some other class, then think again. With Reflection, this is possible.
Using reflection, we can see / view / access a private member, private variable, private method. Some people will not like this with argument that this actually means messing up the laws of encapsulation. I use it for unit testing private methods.
Example follows:
Java Code:import java.lang.reflect.Field; class SimpleKeyPair { private String privateKey = "Tokyo"; // private field } public class PrivateMemberAccessTest { public static void main(String[] args) throws Exception { SimpleKeyPair keyPair = new SimpleKeyPair(); Class c = keyPair.getClass(); // get the reflected object Field field = c.getDeclaredField("privateKey"); // set accessible true field.setAccessible(true); System.out.println("Value of privateKey: " + field.get(keyPair)); // prints "Tokyo" // modify the member varaible field.set(keyPair, "Berlin"); System.out.println("Value of privateKey: " + field.get(keyPair)); // prints "Berlin" } }










Email Blog Entry
License4J 4.0
05-22-2013, 12:23 AM in Java Software