0

I am trying to load classes from a jar file and create instances of those classes. All the classes implement an IModule interface.

The Instance is created succesfully, but whenever I try to cast the object to the IModule type I get ClassCastException.

This is my code:

urlCl = new URLClassLoader(new URL[] { classFile.toURL()},System.class.getClassLoader());
Class projectClass = urlCl.loadClass("Project");
IModule projectObj = (IModule) projectClass.newInstance();

My projects are in eclipse with the IModule being a separate project that is added to the class-path of both the "Project" and the "Loader".

Any suggestions on what I am doing wrong? Thanks.

bwegs
  • 3,769
  • 2
  • 30
  • 33
Petre Popescu
  • 1,950
  • 3
  • 24
  • 38

1 Answers1

1

In Java a class or interface is identified by it's fully qualified name, and the classloader that loaded it.

Probably, you're trying to cast the object to the correct interface but loaded by another classloader.

Take a look at this:

Solution for the ClassCastException due to ClassLoader issue

Community
  • 1
  • 1
Andres
  • 10,561
  • 4
  • 45
  • 63
  • I see. I did not knew that you can't cast one object to another if a different classloader was used. By removing the System.class.getClassLoader() parameter (so that the default one is used), everything worked. Thanks – Petre Popescu Jun 11 '14 at 19:48