Simple java code snippet. It has three classes. After compiling the code please delete A.class and then execute the code. Code still runs, why its not checking whether the byte code of A exists or not?
class A {
static {
System.out.println("In the class A");
}
public A() {
}
}
class B {
private A a = null;
static {
System.out.println("In the class B");
}
开发者_如何学JAVA public B() {
a = new A();
}
}
public class ExampleLinkage {
static {
System.out.println("In the class A");
}
public ExampleLinkage(String str) {
}
public static void main(String args[]) {
try {
System.out.println("In the main method of ExampleLinkage");
Class.forName("com.bt.rtti.B");
} catch(Exception e) {
e.printStackTrace();
}
}
}
I would guess that at no point the class A is needed to be loaded, even though there is an instance of it inside B, since you never instantiate an instance of B.
the JVM is very lazy when it load classes. it loads them either when you instantiate an object of that class (at the first time), when you explicitly load a class with Class.forName() or when you otherwise reference the class in a way that requires information from it (try accessing a static member of A from the static initializer of B and see that A will get loaded.
As your not recompiling it, just running the class.
Class A is not used in the code (i.e. in the main method).
At run-time classes are loaded as they are being used. At that time, you would get a ClassNotFoundError. But if you are not using the class, there is not need for it to be there.
Try to make an instance of B (which needs an instance of A), then you will get an error.
Further to Gordon's answer, you are only running the class, and class A is not required, if you called A's constructor or referenced a static field or method in A, then you would get the ClassNotFoundException
you are expecting
精彩评论