Note that there are some explanatory texts on larger screens.

plurals
  1. POConstructor.newInstance vs Class.newInstance with a SecurityManager
    primarykey
    data
    text
    <p>In Java, when a SecurityManager exists that rejects access check suppression, Constructor's newInstance method works while Class's newInstance throws a SecurityException. Here's an example:</p> <pre><code>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 &amp;&amp; "suppressAccessChecks".equals(perm.getName())) { throw new SecurityException(); } } }); String.class.getConstructor().newInstance(); // works String.class.newInstance(); // throws SecurityException } } </code></pre> <p>Running this produces:</p> <pre><code>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) </code></pre> <p>The JavaDoc for <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29" rel="nofollow">Class.newInstance</a> says that it calls checkMemberAccess and checkPackageAccess on the SecurityManager, but I don't know why it would call <a href="http://download.oracle.com/javase/6/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible%28boolean%29" rel="nofollow">setAccessible</a>. Is there a rationale for this difference in behavior?</p> <p>I'm using:</p> <pre><code>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) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload