View RSS Feed

My Java Tips

Reflection example - accessing private data

Rating: 1 votes, 4.00 average.
by , 05-21-2011 at 05:28 PM (4604 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"
    }
}

Submit "Reflection example - accessing private data" to Facebook Submit "Reflection example - accessing private data" to Digg Submit "Reflection example - accessing private data" to del.icio.us Submit "Reflection example - accessing private data" to StumbleUpon Submit "Reflection example - accessing private data" to Google

Tags: reflection Add / Edit Tags
Categories
Java SE

Comments