Constructor.newInstance vs Class.newInstance with SecurityManager

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(); // works String.class.newInstance(); // throws SecurityException } } 

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) 
+4
source share
1 answer

Class.newInstance() calls SecutrityManager.checkMemberAccess(this, Member.PUBLIC) , which - by default - provides access to all public members. checkPermission() is called (via checkMemberAccess() ) only if the member in question is not public.

Thus, your overriding of checkPermission() will not affect access to public members. You need to override checkMemberAccess() .

Here are the relevant quotes from the Javadocs Class :

( newInstance() failed if) calling s.checkMemberAccess (this one, Member.PUBLIC) prevents the creation of new instances of this class

And SecurityManager :

The default policy ( checkMemberAccess() ) is to allow access to PUBLIC members, as well as access to classes that have the same classloader as the caller. In all other cases, this method calls checkPermission () ...

0
source

Source: https://habr.com/ru/post/1338575/


All Articles