Look at the following code:
public class A
{
private int data=0;
}
Import java.lang.reflect.*;
public class B
{
public static void Main (string[] args)
{
A a1 = new A ();
field[] fields = A1.getclass (). Getdeclaredfields ();
AccessibleObject.setaccessible(Fields, True);
Try
{
System.out.println (fields[0].tostring () + "=" + fields[0].get (A1));
Fields[0].setint (A1, 150);
System.out.print (fields[0].tostring () + "=" + fields[0].get (A1));
catch (Illegalaccessexception Ex1)
{
catch (IllegalArgumentException Ex1)
{
}
}
}
The output of the above code is:
private int reflectiontest. A.data=0
private int reflectiontest. a.data=150
In this process, the object A1 's private Type field value has been modified, whether this is a breach of Java access rules.
Generally, we do not operate on the private fields of a class, nor do we use reflection, but sometimes, for example, to serialize, we must have the ability to handle these fields, and then we need to call the on the AccessibleObject. Setaccessible the () method to allow this access, and because the Field,method and constructor in the reflection class inherit from AccessibleObject, by calling on these classes Setaccessible the () method, we can implement the operations on these fields. But sometimes this can be a security risk, and to do so, we could enable Java.security.manager to determine whether a program has permission to call setaccessible (). By default, the kernel API and the code for the extended directory have this permission, and the Classpath or the application loaded by URLClassLoader does not have this permission. For example, when we execute the above program in this way, the exception is thrown
>java-djava.security.manager exampleexplorer
Exception in thread "main" Java.security.AccessControlException:access denied (
Java.lang.reflect.ReflectPermission suppressaccesschecks)
at java.security.AccessControlContext.checkPermission (Unknown Source)
...