In Java code, the member variables of a class are often placed as private
When you get the value of a private member variable of this class outside of a class, you need to be aware of:
Test class: public class accessibletest { private int id; private String name; public accessibletest () { } public int getid () { return id; } public void setid (int id) { this.id = id; } public string getname () { return name; } &nbsP;public void setname (string name) { this.name = name; } }
Main class: Java code public class main { Public static void main (String[] args) throws Exception { class clazz = class.forname (" Com.test.accessible.AccessibleTest "); Accessibletest at = new accessibletest (); at.setid (1); at.setname ("at"); for (field f : Clazz.getdeclaredfields ()) { f.setaccessible (true);//accessibletest the member variable in the class is private, you must do this system.out.println (F.Getting (at);//Get value } of current field in current object } }
If the Setaccessible (true) method is not called before the field is fetched, the exception: Java code java.lang.IllegalAccessException:Class com.test.accessible.Main Can not access A's class com.test.accessible.AccessibleTest with modifiers "private"
Of course within the Accessibletest class (except for the inner class of the Accessibletest)
You do not need to invoke the Setaccesible () method when doing this
Obviously accessible is not a way to identify whether a method can be accessed. Public method accessible is still false
20 times-fold improvement in performance after using Method.setaccessible (true)
The Accessable property is inherited from the AccessibleObject class. function is to enable or disable security checks
Interpretation in the JDK API
Reference
The AccessibleObject class is the base class for Field, method, and constructor objects. It provides the ability to mark reflected objects to cancel the default Java language access control checks when they are used. For public members, default (packaged) Access members, protected members, and private members, an access check is performed when a field, method, or constructor object is used individually to set or get fields, invoke methods, or create and initialize a new instance of a class.
Setting the accessible flag in a reflection object allows complex applications with sufficient privileges (such as Java Object serialization or