java 加载类失败,Java中何时动态加载引用不存在的类/方法的类失败?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值