类加载器与类型身份
类名相同不保证是同一个类型
对普通具名类,运行时身份由二进制名称与定义它的 ClassLoader 共同确定。同一份字节码被两个不同加载器定义,可以形成两个互不相同的运行时类型;不能只按包名和类名判断能否强转。JVMS 类型创建
发起加载的加载器不一定是最终定义它的加载器。双亲委派使请求可由父级满足,但它是加载策略,不是覆盖所有场景的固定规则。
可运行示例(Java 17)
保存为 LoaderIdentityDemo.java,保留编译生成的内部类文件,然后运行:
import java.io.InputStream;
public class LoaderIdentityDemo {
public static class Payload {}
static class ByteLoader extends ClassLoader {
private final byte[] bytes;
ByteLoader(byte[] bytes) {
super(LoaderIdentityDemo.class.getClassLoader());
this.bytes = bytes;
}
@Override
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> result = findLoadedClass(name);
if (result == null) {
result = name.equals("LoaderIdentityDemo$Payload")
? defineClass(name, bytes, 0, bytes.length)
: super.loadClass(name, false);
}
if (resolve) resolveClass(result);
return result;
}
}
}
public static void main(String[] args) throws Exception {
byte[] bytes;
try (InputStream input = LoaderIdentityDemo.class
.getResourceAsStream("/LoaderIdentityDemo$Payload.class")) {
if (input == null) throw new IllegalStateException("class missing");
bytes = input.readAllBytes();
}
Class<?> first = new ByteLoader(bytes)
.loadClass("LoaderIdentityDemo$Payload");
Class<?> second = new ByteLoader(bytes)
.loadClass("LoaderIdentityDemo$Payload");
System.out.println(first.getName().equals(second.getName()));
System.out.println(first == second);
System.out.println(first.isInstance(second.getConstructor().newInstance()));
}
}输出为 true、false、false。示例仅对一个指定类型使用本地定义,其余继续委派;不是通用插件加载器或安全隔离方案。加载锁、缓存与 defineClass 的契约见 ClassLoader API。
JDK 8 与模块化之后
JDK 8 常见 Bootstrap / Extension / Application 层次;JDK 9 起使用 Platform 加载器替代旧 Extension 机制,不能继续按 rt.jar、lib/ext 描述所有版本。父子关系是委派关系,不是 Java 继承关系。
线程上下文 ClassLoader 为服务发现等提供一种选择加载环境的方式,不等于全局关闭委派。插件边界上的共享接口通常要由共同可见的加载器定义,否则也可能出现“同名接口不能转换”。
热加载与卸载
重新定义同名类通常需要新的加载器环境,旧实例仍属于旧类型;替换文件不会把旧对象自动变成新类型。类卸载还受加载器及其相关对象的可达性等条件限制,清除一个局部变量并不保证卸载。
排查类加载泄漏时,检查线程上下文加载器、静态注册、监听器、缓存与存活线程的引用链。查看异常时同时记录类型名、定义加载器与依赖来源。