Java - Java security manager and private field access

Introduction

Access to inaccessible members of a class is controlled by Java security manager.

By default, the security manager is not installed for your application.

That is why you can access all fields, methods, and constructors of a class using the setAccessible(true) method.

If a security manager is installed for your application, whether you can access an inaccessible class member depends on the permission granted to your application to access such members.

You can check if the security manager is installed for your application by the following code:

SecurityManager securityMgr = System.getSecurityManager();
if (securityMgr == null) {
        System.out.println("Security manager is not installed");
}

Install

You can install a default security manager by passing the ?Djava.security.manager option on the command line.

The security manager uses a Java security policy file to enforce the rules specified in that policy file.


java -Djava.security.manager -Djava.security.policy=c:\myjava.policy com.book2s.reflection.AccessPrivateField

The contents of the myjava.policy file would look as follows:

grant {
        // Grant permission to all programs to access inaccessible class members
        permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
};

To stop the accessing inaccessible members using reflection, comment out the following line in your Java security policy file:

permission java.lang.reflect.ReflectPermission "suppressAccessChecks";

The following code illustrates how to check if your program can access normally inaccessible class members using reflection.

Demo

import java.lang.reflect.ReflectPermission;

public class Main {
  public static void main(String[] args) {
    try {//from  www  . j  a v  a2 s  .  c o m
      // Create a permission object
      ReflectPermission rp = new ReflectPermission("suppressAccessChecks");

      // check for permission
      rp.checkGuard(null);
      System.out.println("Reflect permission is granted");
    } catch (SecurityException e) {
      System.out.println("Reflect permission is not granted");
    }
  }
}

Result

Related Topic