Accessing private variables in Java via reflection

Viewed 35104

I'm trying to write a method that will get a private field in a class using reflection.

Here's my class (simplified for this example):

public class SomeClass {
    private int myField;

    public SomeClass() {
        myField = 42;
    }

    public static Object getInstanceField(Object instance, String fieldName) throws Throwable {
        Field field = instance.getClass().getDeclaredField(fieldName);
        return field.get(instance);
    }
}

So say I do this:

SomeClass c = new SomeClass();
Object val = SomeClass.getInstanceField(c, "myField");

I'm getting an IllegalAccessException because myField is private. Is there a way to get/set private variables using reflection? (I've done it in C#, but this is the first time I've tried it in Java). If you're wondering why there is the need to do such madness :), it's because sometimes during unit testing it's handy to set private variables to bogus values for failure testing, etc.

1 Answers
Related