ClassCastException because of classloaders?(ClassCastException 因为类加载器?)
问题描述
在使用类加载器时,我遇到了以下异常:
While playing with classloaders i got the following exception:
Exception in thread "main" java.lang.ClassCastException: xxx.Singleton cannot be cast to xxx.Singleton
这是否意味着来自类加载器的实例不能转换为另一个类加载器的类?
Does this mean that an instance from a classloader is not castable to an class of another classloader?
检查我的代码,感谢类加载器,我可以在其中实例化 3 个单例,即使使用"安全性也是如此.
Check my code where i'm able to instanciate 3 singletons thanks to classloaders, even with the "" security.
public static void main(String[] args) throws Exception {
URL basePath = new URL("file:/myMavenPath/target/classes/");
Object instance = getClassInstance(Singleton.class);
System.out.println(instance);
//
Object instance2 = getClassInstance(
new URLClassLoader( new URL[]{basePath} , null )
.loadClass("my.Singleton")
);
System.out.println(instance2);
//
Object instance3 = getClassInstance(
new URLClassLoader( new URL[]{basePath} , null )
.loadClass("my.Singleton")
);
System.out.println(instance3);
// Only the 1st cast is ok
Singleton testCast1 = (Singleton) instance;
System.out.println("1st cast ok");
Singleton testCast2 = (Singleton) instance2;
System.out.println("2nd cast ok");
Singleton testCast3 = (Singleton) instance3;
System.out.println("3rd cast ok");
}
private static Object getClassInstance(Class clazz) throws Exception {
Method method = clazz.getMethod("getInstance");
method.setAccessible(true);
return method.invoke(null);
}
class Singleton {
private static final Singleton INSTANCE = new Singleton();
public static Singleton getInstance() {
return INSTANCE;
}
private Singleton() {
Exception e = new Exception();
StackTraceElement[] stackTrace = e.getStackTrace();
if (!"<clinit>".equals(stackTrace[1].getMethodName())) {
throw new IllegalStateException("You shall not instanciate the Singleton twice !",e);
}
}
public void sayHello() {
System.out.println("Hello World ! " + this);
}
}
推荐答案
你不能在类加载器之间进行转换.类标识由完全限定名和类加载器组成.检查类身份危机这里.
You cannot cast between class loaders. Class identity is composed of fully qualified name and the class loader. Check class identity crysis here.
这篇关于ClassCastException 因为类加载器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ClassCastException 因为类加载器?


- Eclipse 插件更新错误日志在哪里? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01