I have a poorly designed class in a 3rd-party JAR and I need to access one of its private fields. For example,
why should I need to choose private field is it necessary?
class IWasDesignedPoorly {
private Hashtable stuffIWant;
}
IWasDesignedPoorly obj = ...;
How can I use reflection to get the value of stuffIWant?
In order to access private fields, you need to get them from the class’s declared fields and then make them accessible:
EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw
Exceptions, although the only checked exceptions you need to be mindful of are commented above.The
NoSuchFieldExceptionwould be thrown if you asked for a field by a name which did not correspond to a declared field.The
IllegalAccessExceptionwould be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out thef.setAccessible(true)line.The
RuntimeExceptions which may be thrown are eitherSecurityExceptions (if the JVM’sSecurityManagerwill not allow you to change a field’s accessibility), orIllegalArgumentExceptions, if you try and access the field on an object not of the field’s class’s type: