28

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.

ROMANIA_engineer
  • 51,252
  • 26
  • 196
  • 186
dcp
  • 53,030
  • 22
  • 140
  • 160

1 Answers1

33

Figured it out. Need

field.setAccessible(true);
dcp
  • 53,030
  • 22
  • 140
  • 160