Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Created April 14, 2016 01:41
Show Gist options
  • Save vxhviet/02b4c9d482170c8bfb935f0c9c715226 to your computer and use it in GitHub Desktop.
Save vxhviet/02b4c9d482170c8bfb935f0c9c715226 to your computer and use it in GitHub Desktop.
Read a private field in Java with reflection.

Source: StackOverflow

Question: I have a poorly designed class in a 3rd-party JAR and I need to access one of its private fields. How can I do that with reflection?

public class StupidClass{
  private RectF stupidRectf;
}

Answer:

In order to access private fields, you need to get them from the class's declared fields and then make them accessible:

Field f = stupidClassObj.getClass().getDeclaredField("stupidRectf"); //NoSuchFieldException
f.setAccessible(true);
RectF r = (RectF) f.get(stupidClassObj); //IllegalAccessException

Both accessing the field, setting it as accessible and retrieving the value will all throw Exceptions, although the only checked exceptions you need to be mindful of are commented above.

The NoSuchFieldException would be thrown if you asked for a field by a name which did not correspond to a declared field.

stupidClassObj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException

The IllegalAccessException would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true) line.

The RuntimeExceptions which may be thrown are either SecurityExceptions (if the JVM's SecurityManager will not allow you to change a field's accessibility), or IllegalArgumentExceptions, if you try and access the field on an object not of the field's class's type:

f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment