2011-02-14 73 views
2

是否有可能在运行时控制加载类的顺序?例如:我有两个Jaras类的SomeClass类:SomeLibrary-1.0.jar和SomeLibrary-2.0.jar。该类具有返回当前版本的SomeLibrary的静态方法getVersion()。我使用找到的解决方案here在运行时修改类路径。现在,当我运行代码:
在运行时修改类路径 - 控制类加载顺序

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

我希望看到输出2.01.0代替。这是因为类加载器使用类路径中找到的第一个类。是否有可能控制已加载的类或已覆盖的类的加载?

+0

你需要使用类似OSGI来处理不同版本的罐子在一个应用程序。 – Augusto 2011-02-14 11:20:13

+0

@aioobe:Pawel已经提到他已经看到你发布的链接,但没有找到解决方案。点击标有`here`的链接。 – 2011-02-14 11:25:29

回答

1

你有两个相同的JAR版本需要使用不同的ClassLoader实例。在这种情况下黑客入侵SystemClassLoader并不能帮到你。

例如,你可以在它自己的URLClassLoader实例加载每个罐子:

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));