为所有类显式使用自定义类加载器

时间:2014-10-15 06:34:39

标签: java classloader

我的应用程序中有两个模块。这些模块共享一些常见的JAR ,其中包含一些静态HashMaps。我希望使用不同的类加载器加载这些模块。每个类加载器都有一个包含一组位置的自定义类路径。

URL [] urlsForModule1=getURLsForModule1();

URL[] urlsForModule2=getURLsForModule2();

Thread.currentThread().setContextClassLoader( new URLClassLoader( urlsForModule1, ClassLoader.getSystemClassLoader().getParent() ) );
//Perform the activities needed for Module 1
String valueForModelue1=CommonClass.getValueFromMap("someKey");
//The value is already set in some other place and this should give a specific value for Module 1

Thread.currentThread().setContextClassLoader( new URLClassLoader( urlsForModule2, ClassLoader.getSystemClassLoader().getParent() ) );
//Perform the activities needed for Module 2
String valueForModelue2=CommonClass.getValueFromMap("someKey");
//The value it should give a specific value for Module 2

但我遇到的问题是Common JAR中的公共类文件。由于这些类文件已经加载(在其他类中的上述代码行之前),因此staic HashMaps保留了它们的previuos值。是否可以告诉下面的所有代码

Thread.currentThread().setContextClassLoader( new URLClassLoader( urlsForModule1, ClassLoader.getSystemClassLoader().getParent() ) );

应该使用上面的URLClassLoader加载类,即使它们已经加载了吗?

0 个答案:

没有答案