When a class loads in the JVM

I have two examples:

Example 1:

public class A {

}

public class B {

  public void m(A a) {

  }

}
public class C {

    public static void main(String[] args) {
            B b = new B();
            System.out.println("hello!");
    }

}

Compile all three classes. Remove A.class. Run main. No exception selected.

Example 2:

public class D {

}

public class E {

    public void omg(D d) {

    }

    public static void main(String[] args) {
        E e = new E();
    }


}

Compile the classes. Remove D.class. Run the main method.

Exception in thread "main" java.lang.NoClassDefFoundError: D
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
    at java.lang.Class.getMethod0(Unknown Source)
    at java.lang.Class.getMethod(Unknown Source)
    at sun.launcher.LauncherHelper.getMainMethod(Unknown Source)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: D
    at java.net.URLClassLoader$1.run(Unknown Source)

Why? D is never mentioned.

+4
source share
2 answers

Your class has a reference to the class Din the method public void omg(D d).

Usually, the Sun / Oracle JVM uses lazy resolution, so it doesn't matter if you don't use this method, however you can see from the stack trace that the main method is executed using a reflexive operation Class.getMethodthat makes the difference.

You can verify this with the following code:

public class B {

  public static void main(String[] args) {
    D.main(args);
  }
}
class D {

  public void foo(E e) {}
  public static void main(String[] args) {
    System.out.println("hello world");
  }
}
class E { }

E.class java B . :

public class B {

  public static void main(String[] args) {
    try {
      D.class.getMethod("main", String[].class);
    } catch(NoSuchMethodException ex) {
      ex.printStackTrace();
    }
    D.main(args);
  }
}
class D {

  public void foo(E e) {}
  public static void main(String[] args) {
    System.out.println("hello world");
  }
}
class E { }

, E , java.lang.NoClassDefFoundError: E java B. , , , D main.


, , public foo. , Class.getMethod public .

: public omg NoClassDefFoundError.

+1

JavaVM. 5. , :

, Java , ( "" "" ), , ( "" "" ).

, Sun/Oracle "" ( "" ) , , .

+4

All Articles