views:

431

answers:

3

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.

Thanks.

+7  A: 

Figured it out. Need

field.setAccessible(true);
dcp
bear in mind that this won't work if there is PermissionManager
Bozho
This can improve the performance marginally even if the member is otherwise accessible (as it turns the checks off)
Peter Lawrey
A: 

A good resource is the Java Almanac (now named exampledepot):

http://www.exampledepot.com/egs/java.lang.reflect/SetAccessible.html

Thorbjørn Ravn Andersen