Nishi
Nishi

Reputation: 125

java Class Loader

A same class name with same package structure is residing in different jar files and both the classes are loadded by different class loader. if i want to import both the classes and use them in different scenario then how can I do this? Please let me know technique.

Eample :
ClassLoader :-TestClassLoaderFirst
package src.test.com;
class TestClass is present in A.jar 
TestClass{
   public void dispaly(){
      System.out.println("In A.jar ")
   }
}


and b.jar.
ClassLoader :-TestClassLoaderSecond
package src.test.com;
Class TestClass{
   public void present(){
      System.out.println("")
}

Upvotes: 1

Views: 584

Answers (2)

Pablo Grisafi
Pablo Grisafi

Reputation: 5047

As Jon Skeet said, (and you really should listen a man with 327k!), don't do that. But if you must...
Assuming your classes look like

public class TestClass {
    public static void display() {
        System.out.println("In A.jar ");
    }
}

and get compiled into target/A.jar, and something like that happens to TestClass in B.jar, you can create a main class in your own package like this:

public class Main {

    public static void main(String[] args) throws MalformedURLException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
        URL urlA = new URL("file:target/A.jar");
        URL urlB = new URL("file:target/B.jar");
        URLClassLoader clA = new URLClassLoader(new URL[] { urlA });
        URLClassLoader clB = new URLClassLoader(new URL[] { urlB });

        clA.loadClass("TestClass").getMethod("display", (Class<?>[]) null).invoke(null, (Object[]) null);
        clB.loadClass("TestClass").getMethod("display", (Class<?>[]) null).invoke(null, (Object[]) null);
    }
}

and you will get

In A.jar
In B.jar

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499830

If you want to use those two classes in a strongly typed way from the same class then I believe you're out of luck.

If each class is only used from within one other class, separately, then you could compile each of those other classes separately, referencing the appropriate jar file, and then create a ClassLoader hierarchy so that at execution time each one ends up loading the right classes.

However, this is a complete pain. If at all possible, you should rename one of the classes to avoid the naming collision. I would be tempted to do that even if it meant rebuilding an open source project. (Change the name of the class from the project which is easiest to rebuild, to save time in the future.)

Upvotes: 1

Related Questions