Does the Setaccessible () method break Java access rules? __java

Source: Internet
Author: User
Tags reflection

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)
...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.