With the reflection mechanism of Java, we can access the private members and private functions of a class.
Accessing private fields
As mentioned above, the class. getfield (string) and Class. getfields () methods can only return public members.
To access a private member, use the class. getdeclaredfield (string) and Class. getdeclaredfields () functions as follows:
Public Class A {private string m; Public A (string m) {This. M = m ;}} public class B {public static void main (string [] ARGs) throws securityexception, nosuchfieldexception, illegalargumentexception, illegalaccessexception {A obja = new A ("Hello ruby"); field =. class. getdeclaredfield ("M"); // The field of the parent class cannot be returned. setaccessible (true); // set the original private field variable to visible string value = (string) field. get (obja); system. out. println (value); // The result is Hello Ruby }}
Accessing private methods
Class. getmethod (string, class [] parametertypes) and Class. getmethods () can only return public methods in one class.
To access the private method, you need class. getdeclaredmethod (string name, class [] parametertypes) and Class. getmethods (), as follows:
public class A {private String m;public A(String m) {this.m = m;}private String f() {return m;}}public class B {public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {A objA = new A("Hello Ruby");Method method1 = A.class.getDeclaredMethod("f", null);method1.setAccessible(true);String value = (String)method1.invoke(objA, null);System.out.println(value);}}