|
| 1 | +import org.junit.jupiter.api.Test; |
| 2 | +import org.junit.jupiter.api.TestReporter; |
| 3 | + |
| 4 | +import java.net.MalformedURLException; |
| 5 | +import java.net.URL; |
| 6 | +import java.net.URLClassLoader; |
| 7 | +import java.nio.file.Path; |
| 8 | +import java.nio.file.Paths; |
| 9 | + |
| 10 | +import static org.junit.jupiter.api.Assumptions.assumeTrue; |
| 11 | + |
| 12 | +public class NullParentClassLoaderIT { |
| 13 | + |
| 14 | + /** |
| 15 | + * Attempt to load a class from the URLClassLoader that references a java.sql.* class. The |
| 16 | + * java.sql.* package is one of those not visible to the Java 9 bootstrap class loader that |
| 17 | + * was visible to the Java 8 bootstrap class loader. |
| 18 | + */ |
| 19 | + @Test |
| 20 | + public void loadSqlDateUsingNullParent(TestReporter reporter) throws Exception { |
| 21 | + URLClassLoader loader = buildLoader(reporter); |
| 22 | + |
| 23 | + Class<?> jsqlUserClass = loader.loadClass("JavaSqlUser"); |
| 24 | + reporter.publishEntry("Loaded class", jsqlUserClass.toString()); |
| 25 | + |
| 26 | + Object jsqlUser = jsqlUserClass.getConstructor().newInstance(); |
| 27 | + reporter.publishEntry("Created instance", jsqlUser.toString()); |
| 28 | + |
| 29 | + loader.close(); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Build a URLClassLoader that only includes the null-parent-classloader artifact in its classpath, |
| 34 | + * along with the bootstrap class loader as its parent. |
| 35 | + * |
| 36 | + * @throws MalformedURLException |
| 37 | + * on failure to build the classpath URL |
| 38 | + */ |
| 39 | + private URLClassLoader buildLoader(TestReporter reporter) throws MalformedURLException { |
| 40 | + String testRootFolder = NullParentClassLoaderIT.class.getResource("/").getPath(); |
| 41 | + reporter.publishEntry("Test classes folder", testRootFolder); |
| 42 | + Path projectJar = Paths |
| 43 | + .get(testRootFolder) |
| 44 | + .getParent() |
| 45 | + .resolve("null-parent-classloader-1.0-SNAPSHOT.jar"); |
| 46 | + |
| 47 | + assumeTrue( |
| 48 | + projectJar.toFile().exists(), |
| 49 | + "Project JAR must exist as " + projectJar.toString() + " for test to be executed."); |
| 50 | + reporter.publishEntry("Project JAR", projectJar.toString()); |
| 51 | + |
| 52 | + URL path[] = { projectJar.toUri().toURL() }; |
| 53 | + // this is the parent that is required when running under Java 9: |
| 54 | + // ClassLoader parent = ClassLoader.getPlatformClassLoader(); |
| 55 | + ClassLoader parent = null; |
| 56 | + URLClassLoader loader = new URLClassLoader(path, parent); |
| 57 | + reporter.publishEntry("Class loader", loader.toString()); |
| 58 | + |
| 59 | + return loader; |
| 60 | + } |
| 61 | + |
| 62 | +} |
| 63 | + |
0 commit comments