ClassLoader
clMain -> URLClassLoader
clA (class A, $B).
$B is a inner class B of the class A.
- From clMain creating new clA with specified url to the jar file which contains class A (and class $B). Then creating new object A via clA.
- Another class, loaded from X
ClassLoader
, execute a method of the object A via interface without problems. - Then, in that method, should be created new object $B, but it throws the
NoClassDefFoundError
. - Loading the class $B in the constructor of the class A is solving the problem:
this.getClass().getClassLoader().loadClass("A$B");
So, the cuestion is: "Why the definition of the class $B cannot be found for step 3 and Can be solved this porblem in another way?"
Checking the ClassLoader
used in the method (this.getClass().getClassLoader()
) and comparing it with the ClassLoader
used in the constructor - is the same and contains the necessary url.
Java 8 and 14 tried to run, jdk 8 to build.
Edit:
public class A {
public A(){
this.getClass().getClassLoader().loadClass("A$B"); // success
}
public void foo(){
this.getClass().getClassLoader().loadClass("A$B"); // success
new B(); // success
}
public static final class B {}
}
public class A {
public A(){
}
public void foo(){
this.getClass().getClassLoader().loadClass("A$B"); // throw
new B(); // Edit: added this line to demostrate what is not the main diff between two examples
}
public static final class B {}
}
Edit: this behavior is not related specifically to inner class, but to every class located in the jar. In simple words, i need to iterate every class located in the jar and load them manually before they are used, or else jvm will throw the NoClassDefFoundError
.