kosmo
kosmo

Reputation: 13

java.lang.ClassCastException when casting Object-result of java.lang.reflect.Method.invoke

I load dynamically an external class from my eclipse rcp application with urlClassLoader. The invoke()-method returns an Object of self-defined Type.

ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();  
URLClassLoader cl = URLClassLoader.newInstance( url);  
Thread.currentThread().setContextClassLoader(cl);  
String className ="myClass";
Class<?> c = cl.loadClass(className);
Object inst =c.newInstance();
Method run =c.getMethod("run", new Class[0]);
Object rdsObject =run.invoke(inst, new Object[]{});
Thread.currentThread().setContextClassLoader( oldClassLoader );
rts.data.RTSDataSet rds =(rts.data.RTSDataSet) rdsObject;

When I'm trying to cast this Object, I get the java.lang.ClassCastException : rts.data.RTSDataSet cannot be cast to rts.data.RTSDataSet. It seems to me, that the reason is that I have here different ClassLoader. My Question is : how should I set the ClassLoader properly?
Thanks for helping!

Upvotes: 1

Views: 2607

Answers (1)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

Use the two-argument form of URLClassLoader.newInstance to set the parent class loader to be that of the calling code.

 URLClassLoader loaders = URLClassLoader.newInstance(path, this.getClass().getClassLoader());

Upvotes: 1

Related Questions