From the principle of design, if the member variable of a class is designed to be private, then we cannot get the value of this private variable outside the class. The usual practice is to provide the get and set methods for this private variable. But if this class does not provide get and set methods, how do we obtain the private member variable for that class? For example, there is a class person:
Class person{
Private String name = "Cross";
}
How do we not get the value of name in this class? Can be obtained by means of the Java reflection mechanism, note that this will be field.setaccessible (true) for the name of this field, so that we can access the private variable
Package com.withiter.test;
Import Java.lang.reflect.Field;
public class Reflecttest {public
static void Main (string[] args) {
try {
class<?> obj = Class.forName (" Com.withiter.test.Person ");
Field[] f = obj.getdeclaredfields ();
for (Field field:f) {
field.setaccessible (true);
System.out.println (Field.getname () + ":" +field.get (Obj.newinstance ()));
}
catch (ClassNotFoundException e) {
//TODO auto-generated catch block
e.printstacktrace ();
} catch ( IllegalArgumentException e) {
//TODO auto-generated catch block
e.printstacktrace ();
} catch ( Illegalaccessexception e) {
//TODO auto-generated catch block
e.printstacktrace ();
} catch ( Instantiationexception e) {
//TODO auto-generated catch block
e.printstacktrace ();
}}} Class person{
Private String name = "Cross";
}