Modify classpath at runtime - controlling class loading order

后端 未结 1 848
执笔经年
执笔经年 2021-01-15 12:04

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 cl

相关标签:
1条回答
  • 2021-01-15 12:45

    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));
    
    0 讨论(0)
提交回复
热议问题