2

Is it possible to controll order of loaded classes at runtime? For example: I have class SomeClass which is in two jaras: SomeLibrary-1.0.jar and SomeLibrary-2.0.jar. The class have static method getVersion() which returns current version of SomeLibrary. I use solution found here to modify classpath at runtime. Now, when I run the code:

public static void main(String[] args) {
    ClassPathHacker.addFile("SomeLibrary-1.0.jar");
    ClassPathHacker.addFile("SomeLibrary-2.0.jar");
    System.out.println(SomeClass.getVersion());
}

I expect to see output 2.0 but there is 1.0 instead. This is because class loader use first class found in the class path. Is it possible to control oreder of loaded classes or 'overwrite' class already loaded?

Community
  • 1
  • 1
Pawel
  • 33
  • 1
  • 4
  • You'll need to use something like OSGI to handle the different versions of a jar in one application. – Augusto Feb 14 '11 at 11:20
  • @aioobe: Pawel has mentioned that he had seen the link you have posted but not found nay solution. Click on the link labeled `here` in question. – Harry Joy Feb 14 '11 at 11:25

1 Answers1

1

You you have two versions of the same JAR you need to use different ClassLoader instances. hacking the SystemClassLoader does not help you in that case.

For example you can load each jar in it's own URLClassLoader instance:

URLClassLoader ucl1 = new URLClassLoader(new URL[] { new URL("SomeLibrary-1.0.jar") });
URLClassLoader ucl2 = new URLClassLoader(new URL[] { new URL("SomeLibrary-2.0.jar") });

Class<?> cl1 = ucl1.loadClass("org.example.SomeClass");
Class<?> cl2 = ucl2.loadClass("org.example.SomeClass");

Method m1 = cl1.getMethod("getVersion");
System.out.println("v1: " + m1.invoke(cl1));
Method m2 = cl2.getMethod("getVersion");
System.out.println("v2: " + m2.invoke(cl1));
Robert
  • 39,162
  • 17
  • 99
  • 152
  • Correct. Do you know if there is a way to change the system class loader with one of these classloader instances? Since, I cannot specify the classloader for the library which I use (javax.script.ScriptManager). – dmarrazzo Jan 22 '15 at 16:07