gpt4 book ai didi

java - 关于类加载的困惑

转载 作者:搜寻专家 更新时间:2023-10-31 20:10:30 24 4
gpt4 key购买 nike

我对 JVM 实际加载类的时间感到有点困惑。我注意到类加载器会在类被引用时加载类。

我正在使用 java6 环境并使用 -verbose:class 运行以跟踪类加载。例如:

MyObject obj = new MyObject(); //MyObject.class will be loaded

但是,在这种情况下

// ClassC.java
package com.gogog22510.test;
public class ClassC {}

// ClassB.java
package com.gogog22510.test;
public class ClassB extends ClassC {}

// ClassA.java
package com.gogog22510.test;
public class ClassA {
public ClassC test() {
return new ClassB();
}
}

当我的测试程序初始化 ClassA 时,它会加载所有 ClassA、ClassB 和 ClassC,即使我没有调用 test()

// TestClassLoad.java
package com.gogog22510.test;
public class TestClassLoad {
public static void main(String[] args) {
// initialize ClassA
System.out.println("start load ClassA");
new ClassA();
}
}

console:

[Loaded TestClassLoad from file:/.../bin/]
start load ClassA
[Loaded ClassA from file:/C:/.../bin/]
[Loaded ClassC from file:/C:/.../bin/]
[Loaded ClassB from file:/C:/.../bin/]

但是如果我像这样更改 test() 方法的返回类型:

// ClassA.java
package com.gogog22510.test;
public class ClassA {
public ClassB test() {
return new ClassB();
}
}

ClassLoader 只会将 ClassA 加载到 perm 空间,除非我调用 test() 方法。

console:

[Loaded TestClassLoad from file:/.../bin/]
start load ClassA
[Loaded ClassA from file:/C:/.../bin/]

为什么 ClassLoader 在我显式调用该方法之前加载所有三个类?

最佳答案

我认为它发生在验证步骤中,以确保 ClassCClassB 的子类,以验证返回类型。

Here ,他们说:

If the method returns a reference type, it must do so using an areturn instruction, and the type of the returned value must be assignment compatible (JLS §5.2) with the return descriptor (§4.3.3) of the method.

另见 this :

Verification (§4.10) ensures that the binary representation of a class or interface is structurally correct (§4.9). Verification may cause additional classes and interfaces to be loaded (§5.3) but need not cause them to be verified or prepared.

关于java - 关于类加载的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31435185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com