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
?
By using Public Method We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class.
We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.
We have used the getter and setter method to access the private variables. Here, the setter methods setAge() and setName() initializes the private variables. the getter methods getAge() and getName() returns the value of private variables.
In order to access private fields, you need to get them from the class's declared fields and then make them accessible:
Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException f.setAccessible(true); Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException
EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw Exception
s, 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.
obj.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 RuntimeException
s which may be thrown are either SecurityException
s (if the JVM's SecurityManager
will not allow you to change a field's accessibility), or IllegalArgumentException
s, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With