跨类加载器? [英] cast across classloader?
问题描述
我该怎么做:
class Foo {
public static Foo get() throws Exception {
ClassLoader cl = new URLClassLoader(new URL[]{"foo.jar"}, null); // Foo.class is in foo.jar
return (Foo)cl.loadClass("Foo").newInstance(); // fails on class cast
}
}
我需要的是JVM从cl中考虑Foo实例,就好像它是来自执行代码的类加载器的Foo实例一样。
What I need is for the JVM to consider the Foo instance from cl as if it is an instance of Foo from the classloader of the executing code.
我见过这些方法,对我来说都没有好处(上面的例子是一个玩具示例):
I have seen these approaches, none of them good for me (the above example is a toy example):
- 通过类加载器加载类(或单独的接口),类加载器是调用代码和创建的类加载器的父类
- 序列化和反序列化对象。
推荐答案
不可能。类标识由完全限定名称和类加载器组成。
Not possible. Class identity consists of the fully qualified name and the class loader.
将对象转换为具有由不同类加载器加载的相同名称的类与尝试转换字符串
到整数
,因为尽管名称相同,这些类确实可能完全不同。
Casting an object to a class with the same name loaded by different classloaders is no different than trying to cast a String
to Integer
, because those classes really could be completely different despite having the same name.
这篇关于跨类加载器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!