我有2个不同的Java项目,一个有2个类:dynamicbeans.DynamicBean2和dynamic.Validator.
在另一个项目中,我动态加载这两个类并将它们存储在一个 Object
class Form {
Class beanClass;
Class validatorClass;
Validator validator;
}
Run Code Online (Sandbox Code Playgroud)
然后我继续创建一个Validator对象validatorClass.newInstance()并使用它validator然后我创建一个bean对象并使用beanClass.newInstance()并将其添加到会话中.
portletRequest.setAttribute("DynamicBean2", bean);
Run Code Online (Sandbox Code Playgroud)
在Form项目的生命周期中,我调用validator.validate()从会话中加载先前创建的bean对象(我正在运行Websphere Portal Server).当我尝试将此对象强制转换为DynamicBean2失败并出现ClassCastException时.
当我将对象拉回会话时使用
faces.getApplication().createValueBinding("#{DynamicBean2}").getValue(faces);
Run Code Online (Sandbox Code Playgroud)
并使用.getClass()我得到检查它的类dynamicbeans.DynamicBean2.这是我想要将它强制转换为的类,但是当我尝试获取ClassCastException时.
我得到这个的原因是什么?
我怎样才能做到这一点:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我需要的是让JVM从cl中考虑Foo实例,就好像它是来自执行代码的类加载器的Foo实例一样.
我见过这些方法,对我来说都没有好处(上面的例子是玩具示例):
在使用类加载器时,我遇到以下异常:
Exception in thread "main" java.lang.ClassCastException: xxx.Singleton cannot be cast to xxx.Singleton
Run Code Online (Sandbox Code Playgroud)
这是否意味着类加载器中的实例不能转换为另一个类加载器的类?
检查我的代码,我可以通过类加载器实现3个单例,即使是""安全性.
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 = …Run Code Online (Sandbox Code Playgroud) 我有两个ClassLoader加载相同的类.所以,显然这些不能相互投射.但是我需要访问在另一个ClassLoader中创建的对象.
我可以访问两个ClassLoader.如何在其他类中使用该对象?我不需要将对象转换为与当前ClassLoader匹配.
但问题是返回的对象的类型是Object.所以,我必须抛弃该对象来访问某些方法.我怎样才能做到这一点?像下面这样的正常转换会导致ClassCastException,我已经知道了.
Mojo mojo = (Mojo) descriptor.getMojo();
Run Code Online (Sandbox Code Playgroud)
descriptor#getMojo()返回一个类型的对象,Mojo但该方法返回Object.怎么办呢?
如果您需要进一步的信息,请告诉我.
我已经阅读了有关类加载的所有理论,但没有一个为此指定了适当的解决方案.