是否有可能在运行时控制已加载类的顺序?例如:我有两个jaras中的类SomeClass : SomeLibrary-1.0.jar和SomeLibrary-2.0.jar。该类具有静态方法getVersion(),该方法返回SomeLibrary的当前版本。我使用solution found 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.0,但实际上看到的是1.0。这是因为类加载器使用在类路径中找到的第一个类。是否可以控制已加载类的顺序或“覆盖”已加载的类?
发布于 2011-02-14 21:45:21
同一个JAR有两个版本,需要使用不同的ClassLoader实例。在这种情况下,黑客攻击SystemClassLoader对您没有任何帮助。
例如,您可以将每个jar加载到它自己的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));https://stackoverflow.com/questions/4991527
复制相似问题