Suppose I dynamically load a Java class C, that references non-existent class/methods. Such a case might occur when C was written for a newer version of Java. When will it fail - as soon as C is loaded, or when a method that calls a non-existent class/method is run? Does this change with the VM - including other versions of Java, such as Java ME?
解决方案
When will it fail?
as soon as C is loaded?
No. Only if when loaded it makes reference to the non existing class ( ie. you have a class attribute of that type )
or when a method that calls a non-existant class/method is run?
Yes. This will be the case.
For instance this runs well.
C:\>more > A.java
class A {}
^C
C:\>more > B.java
class B {
public void method() {
A a = new A();
}
public void other() {
System.out.println("Hello there");
}
public static void main( String ... args ) {
B b = new B();
b.other();
}
}
C:\>javac A.java B.java
C:\>erase A.class
C:\>java B
Hello there
The class B is loaded by java but since none of the code used method it works well.
As opposed to:
C:\>more > A.java
class A {}
C:\>more > B.java
class B {
void method() {
A a = new A();
}
public static void main( String ... args ) {
B b = new B();
b.method();
}
}
^C
C:\>javac A.java B.java
C:\>erase A.class
C:\>java B
Exception in thread "main" java.lang.NoClassDefFoundError: A
at B.method(B.java:3)
at B.main(B.java:7)
Caused by: java.lang.ClassNotFoundException: A
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 2 more
Fails because B attempted to access A.