How can I use Java's reflection capabilities to read/modify a private variable that I normally wouldn't have permission to?

Chandra Patni

Setting the accessible flag in a reflected object of java.lang.reflect.AccessibleObject class allows us to read/modify a private variable that we normally wouldn't have permission to. However, the access check can only be supressed if approved by installed SecurityManager.

java.lang.reflect.Field, java.lang.reflect.Method and java.lang.reflect.Constructor classes inherit this behavior from java.lang.reflect.AccessibleObject class. The following example demonstrates read/modify access to a priavate variable which is normally inaccessible.

import java.lang.reflect.Field;
class SimpleKeyPair {
    private String privateKey = "Cafe Babe"; // 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 "Cafe Babe"
        // modify the member varaible
        field.set(keyPair, "Java Duke");
        System.out.println("Value of privateKey: " + field.get(keyPair)); // prints "Java Duke"
    }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact