2017  Kodetalk | Feedback | Privacy Policy | Terms | About

How do I read a private field in Java?

I have some requirement where need to access the private field and come to know that

it can only achieve through Java Reflection.But seems I am beginner to this failed.

Please suggest how can I able to read the private fields too from anther classes.


Using the Reflection in Java you can access all the private/public fields and methods of one class to another. To access private fields, you need to get them from the class's declared fields and then make them accessible:

Field field = obj.getClass().getDeclaredField("fieldName"); //NoSuchFieldException
field .setAccessible(true);
Hashtable fieldAccess = (Hashtable) field.get(obj); //IllegalAccessException

Please note : 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 field.setAccessible(true) line.

There is no doubt that by using the above code we can able to access any field.But as per oracle documentation it says that,

"Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform"

Answer is