In Java, when there is a SecurityManager that rejects the suppression of access control, the Constructor newInstance method works, while the Class newInstance throws a SecurityException. Here is an example:
import java.lang.reflect.ReflectPermission; import java.security.Permission; public class Test { public static void main(String[] args) throws Exception { System.setSecurityManager(new SecurityManager() { @Override public void checkPermission(Permission perm) { if (perm instanceof ReflectPermission && "suppressAccessChecks".equals(perm.getName())) { throw new SecurityException(); } } }); String.class.getConstructor().newInstance();
Running this process:
Exception in thread "main" java.lang.SecurityException at Test$1.checkPermission(Test.java:10) at java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject.java:125) at java.lang.Class$1.run(Class.java:351) at java.security.AccessController.doPrivileged(Native Method) at java.lang.Class.newInstance0(Class.java:348) at java.lang.Class.newInstance(Class.java:325) at Test.main(Test.java:16)
The JavaDoc for Class.newInstance says that it calls checkMemberAccess and checkPackageAccess in the SecurityManager, but I don't know why it would call setAccessible . Is there a rationale for this difference in behavior?
I use:
java version "1.6.0_20" OpenJDK Runtime Environment (IcedTea6 1.9.5) (ArchLinux-6.b20_1.9.5-1-x86_64) OpenJDK 64-Bit Server VM (build 17.0-b16, mixed mode)
source share