Search code examples
javaclassclassloaderconflict

resolving class name clashes in java


I have a situation where I have to load a named class. If there are multiple classes with the same name (say, com.example.myclass) in my class path I have to load both. I am using 'loadClass()' method of my CustomLoader class which derives from java.lang.ClassLoader. I have not changed the behaviour of the parent class but am simply calling the parent's methods. My problem is that if there are two classes with the same name, I am able to load only one of them. I have scanned the web for a solution but haven't found any. I found many solutions on reloading classes by creating a new class loader instance but in my case the new instance will probably end up loading the first class again. Can this problem be solved?

EDIT: I forgot to mention that the two classes with the same name are in different jar files.

EDIT: Both Jon and Stephen gave the same solution but I can mark only one as answer. Sorry :(. I have up voted both answers though.


Solution

  • I believe the JVM and class libraries assume that a class name is unique within a classloader. Therefore if you want to load the same class name for different classes, you'll need different classloaders (e.g. one for each jar file).

    Using them could be tricky, but that's the sort of problem you get with this sort of thing.