Generally, Private member variables of the callback class and private methods of the call class are not allowed. However, the Java reflection API can bypass this restriction. The getmethods, getfields, getconstructors and other methods used previously are the public methods, class members, and constructors of the returned class.
This article describes how to use the Java reflection API to access private members of the callback class.
1. Access Private Members
Getdeclaredfield (string name) and getdeclaredfields of the class can return all the member variables of the class, including private member variables.
Public class privateobject {</P> <p> private string privatestring = NULL; </P> <p> Public privateobject (string privatestring) {<br/> This. privatestring = privatestring; <br/>}</P> <p> .... </P> <p> privateobject = new privateobject ("the private value"); </P> <p> Field privatestringfield = privateobject. class. <br/> getdeclaredfield ("privatestring"); </P> <p> privatestringfield. setaccessible (true); </P> <p> string fieldvalue = (string) privatestringfield. get (privateobject); <br/> system. out. println ("fieldvalue =" + fieldvalue );
AboveCodePrivatestring is a private member of the privateobject class. Note thatPrivatestringfield. setaccessible (true );
You must enable access control for a class member before accessing this private member. Only the Java reflection API can be used for private members of the callback class.
2. Private methods of the category class
The getdeclaredmethod (string name) and getdeclaredmethods of the same class can be used to define the class-level private method.
Public class privateobject {</P> <p> private string privatestring = NULL; </P> <p> Public privateobject (string privatestring) {<br/> This. privatestring = privatestring; <br/>}</P> <p> private string getprivatestring () {<br/> return this. privatestring; <br/>}</P> <p>... <br/> privateobject = new privateobject ("the private value"); </P> <p> method privatestringmethod = privateobject. class. <br/> getdeclaredmethod ("getprivatestring", null); </P> <p> privatestringmethod. setaccessible (true); </P> <p> string returnvalue = (string) <br/> privatestringmethod. invoke (privateobject, null); </P> <p> system. out. println ("returnvalue =" + returnvalue );
You also need to callPrivatestringmethod. setaccessible (true );You can access the private member method only after you enable access control for this private method.