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");
field.setAccessible(true);
Object value = field.get(myClass);
System.out.println(value);

 

Access to private methods

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