1

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!

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't this have worked URLClassLoader cl = URLClassLoader.newInstance(url, oldClassLoader);?
The Elite Gentleman Depends what that oldClassLoader was... You almost never want to rely upon Thread.getContextClassLoader.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.