Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JDK-8281001 Class::forName(String) defaults to system class loader if the caller is null #8711

Closed
wants to merge 9 commits into from
5 changes: 4 additions & 1 deletion src/java.base/share/classes/java/lang/Class.java
Expand Up @@ -380,7 +380,10 @@ public static Class<?> forName(String className)
@CallerSensitiveAdapter
private static Class<?> forName(String className, Class<?> caller)
throws ClassNotFoundException {
return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
ClassLoader loader = (caller == null) ?
ClassLoader.getSystemClassLoader() :
ClassLoader.getClassLoader(caller);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Formatting nit:

   ClassLoader loader = (caller == null) ? ClassLoader.getSystemClassLoader()
                                         : ClassLoader.getClassLoader(caller);

return forName0(className, true, loader, caller);
}

/**
Expand Down
Expand Up @@ -25,6 +25,7 @@
/**
* @test
* @bug 8281006
* @bug 8281001
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* @bug 8281001
* @bug 8281006 8281001

@bug can have one or more bug IDs

* @summary Test uses custom launcher that starts VM using JNI that verifies
* Module::getResourceAsStream and Class::getResourceAsStream with
* a null caller class functions properly.
Expand Down
Expand Up @@ -108,6 +108,20 @@ int main(int argc, char** args) {
}
assert(n != NULL);

// 8281001
// Try and load a class using Class::forName in the module n which should be
// found with the system classloader (to match FindClass() used above).
// Class exp = Class.forName("open.OpenResources");
jmethodID mid_Class_forName = (*env)->GetStaticMethodID(env, class_Class, "forName", "(Ljava/lang/String;)Ljava/lang/Class;" );
assert(mid_Class_forName != NULL);
jclass oc =(*env)->CallStaticObjectMethod(env, class_Class, mid_Class_forName,
(*env)->NewStringUTF(env, "open.OpenResources"));
if ((*env)->ExceptionOccurred(env) != NULL) {
printf("ERROR: Exception was thrown calling Class::forName.\n");
(*env)->ExceptionDescribe(env);
exit(-1);
}

// Attempt to fetch an open resource from the module. It should return a valid stream.
// InputStream in = n.getResourceAsStream("open/test.txt");
jclass class_Module = (*env)->FindClass(env, "java/lang/Module");
Expand Down