What happens if import instructions cannot be resolved?

I do not understand the following:
The class is loaded by the JVM if necessary, like lazy initialization, right?
Now, if class A makes an import class B , which class B is not actually on the file system (e.g. B.class was deleted or not delivered, or for some reason)
does class A load and start if class B method is not called?
Or class A cannot start at all, since import cannot be allowed?
Or does class A load and run to a certain point?

+4
source share
2 answers
Operator

import important only to the compiler. In the bytecode, all references to other classes are fully qualified. That super-dense imports do not matter at runtime.

In your case, the JVM will try to load all the classes that need to be loaded and check A so he will try to load B immediately , but dependent classes are loaded lazily only when they are needed. See the following example:

 public class A { public static void bar() { new B().foo(); } public static void main(String[] args) { //bar(); } } 

Compile A.java and uninstall B.class . Without calling the bar() method, your program will work fine. But as soon as you uncomment the part of the code using class B , you will be disgusted:

 Exception in thread "main" java.lang.NoClassDefFoundError: B at A.bar(A.java:4) at A.main(A.java:8) Caused by: java.lang.ClassNotFoundException: B at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) ... 2 more 

If B not available, you will get NoClassDefFound or the like.

+7
source

If A.class requires B.class, which is missing. Unable to load A.class file.

The loading class is recursion operation .

When A.class requires B.class, search for B.class JVM in PermGen . If B.class is loaded and stored in PermGen , the JVM will not reload B.class, but will receive it from PermGen directly, otherwise the JVM will load B.class recursively.

When the JVM cannot find B.class, it throws a NoClassDefFoundError .

Read more about NoClassDefFoundError in [Java Specification]: page 319 .

0
source

Source: https://habr.com/ru/post/1436303/


All Articles