I am trying to load classes from a dynamically loaded jar file. Currently I can load a class that doesn't extend to a class other than the root class Object, but I can't load a class that extends a custom class. The detail description of my problem is as follows.
In project A, there is a class A like:
class A {
}
In project B, there are a class B1 and a class B2 like:
class B1 {
}
class B2 extends A {
}
I exported the project A to a.jar, and the project B to b.jar. The testing code is:
File f = new File("Z:\\Jars\\b.jar");
URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { f.toURL() },
System.class.getClassLoader());
Class<?> classB1 = (Class<?>) urlClassLoader.loadClass("b.B1");
System.out.println("B1 is loaded");
Class<?> classB2 = (Class<?>) urlClassLoader.loadClass("b.B2");
System.out.println("B2 is loaded");
The class B1 is loaded successfully, but the class B2 is not loaded due to class a.A is not found exception:
java -cp a.jar;b.jar; a.Main
B1 is loaded
Exception in thread "main" java.lang.NoClassDefFoundError: a/A
Caused by: java.lang.ClassNotFoundException: a.A
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 12 more
How can I resolve this issue? Thanks.
PS. With the inclusion of a.jar, the class B2 can be loaded but fails the following test:
Class<A> classB2 = (Class<A>) urlClassLoader.loadClass("b.B2");
A ab2 = classB2.newInstance();
The first line is fine but the second line triggered the following exception:
Exception in thread "main" java.lang.ClassCastException: b.B2 cannot be cast to a.A
at a.Main.main(Main.java:22)
B2 is supposed to be an A instance, any idea why this happened?