...
In the presence of a security manager s
, the Class.newInstance()
method throws a security exception when either:
- invocation of
s.checkMemberAccess(this, Member.PUBLIC)
denies creation of new instances of this class- the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of
s.checkPackageAccess()
denies access to the package of this class
For this the first condition, "The default policy is to allow access to PUBLIC members, as well as access to classes that have the same class loader as the caller.". This may be unsafe, as was demonstrated in this noncompliant code example. For the second condition, sometimes it is inappropriate to rely on the class loader comparison. The checkPackageAccess()
method should be independently called.
Compliant Solution
This compliant solution checks whether the Class object has any public
constructors. If it does, the java.beans.Beans
API is used to explicitly specify the class loader that should be used to instantiate the class object. If no public
constructors are present, the security manager's checkPackageAccess()
method is invoked to ensure that the caller has sufficient permissions to access members of the package Safe
.
...