在运行时修改类路径-控制类加载顺序 [英] Modify classpath at runtime - controlling class loading order

查看:80
本文介绍了在运行时修改类路径-控制类加载顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我希望看到输出 2.0 ,但是而是 1.0 。这是因为类加载器使用在类路径中找到的第一类。

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?

推荐答案

您有相同版本的两个版本吗? JAR您需要使用不同的ClassLoader实例。

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.

例如,您可以在其自己的URLClassLoader实例中加载每个jar:

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

这篇关于在运行时修改类路径-控制类加载顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆