How to access to class private members in Java

It is possible to use to access class private instance variables and methods using Reflexion.

Access to private instance variables

MyClass myClass = new MyClass();
Field field = MyClass.class.getDeclaredField("myField");
Object value = field.get(myClass);


Access to private methods

MyClass myClass = new MyClass();
Method method = myClass.getClass().getDeclaredMethod("myMethodName");
Object o = method.invoke(object);


You like this content ? Share it with you entourage !