Java中动态引用了不存在的类/方法的类何时会失败? [英] When does a dynamically loaded class that references a non-existent classes/methods fail in Java?

查看:152
本文介绍了Java中动态引用了不存在的类/方法的类何时会失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我动态加载一个Java类C,该类引用了不存在的类/方法.当为较新版本的Java编写C时,可能会发生这种情况.它何时会失败-加载C时,还是运行调用不存在的类/方法的方法时会失败?这会随着VM(包括其他Java版本,例如Java ME)而改变吗?

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?

推荐答案

何时会失败?

加载C之后是什么?

不.仅在加载时,它会引用不存在的类(即,您具有该类型的class属性)

No. Only if when loaded it makes reference to the non existing class ( ie. you have a class attribute of that type )

还是运行调用不存在的类/方法的方法?

是的.会是这种情况.

例如,运行良好.

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

B类是由Java加载的,但是由于没有代码使用method,因此效果很好.

The class B is loaded by java but since none of the code used method it works well.

相对于:

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

失败,因为B尝试访问A.

Fails because B attempted to access A.

这篇关于Java中动态引用了不存在的类/方法的类何时会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆