Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (5.3k points)

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?

1 Answer

0 votes
by (9.5k points)

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

Browse Categories

...