问题描述
我有一个要求,必须根据从UI捕获分发的分发来更改jar.
I have a requirement where jars have to be changed based on distribution where distribution is captured from UI.
分布从一组到另一组.如果选择了一个发行版,则必须动态/以编程方式将与该发行版相关的jar添加到类路径中.
Distribution varies from one group to another. If a distribution is selected then jars related to that distribution have to be added to the class-path dynamically/programmatically.
如果选择了另一个发行版,则必须动态地从类路径中删除以前添加到类路径中的jar,并且必须动态添加与新发行版相关的新jar.分布.
If another distribution is selected then the previous jars which were added to the class-path have to be removed from class-path dynamically and new jars related to new distribution have to be added dynamically.The same has to be continued for other distributions.
任何人都可以建议这是否可能吗?
Can anyone suggest whether this is possible?
推荐答案
天真的方法是将ClassLoader委派给特定于发行版的ClassLoader.这是此类课程的草稿:
A naive approach would be a ClassLoader that delegates to distribution-specific ClassLoaders. Here's a rough draft of such a class:
public class DistributionClassLoader extends ClassLoader {
public DistributionClassLoader(ClassLoader parent) {
super(parent);
}
private Map<String, ClassLoader> classLoadersByDistribution =
Collections.synchronizedMap(new WeakHashMap<>());
private final AtomicReference<String> distribution = new AtomicReference<>();
@Override
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
final ClassLoader delegate = classLoadersByDistribution.get(distribution.get());
if (delegate != null) return Class.forName(name, true, delegate);
throw new ClassNotFoundException(name);
}
public void addDistribution(String key, ClassLoader distributionClassLoader){
classLoadersByDistribution.put(key,distributionClassLoader);
}
public void makeDistributionActive(String key){distribution.set(key);}
public void removeDistribution(String key){
final ClassLoader toRemove = classLoadersByDistribution.remove(key);
}
}
但是,仍然存在几个问题:切换发行版时,我们希望卸载先前发行版中的所有类.我认为没有办法实现这一目标.另外:如果您对委托ClassLoader创建的对象有任何引用,则这些对象将保留对其ClassLoader的引用.我不确定是否有合适的解决方案,但这可能会让您入门.
Several problems remain, however: when switching distributions, we'd want to unload all classes from the previous distribution. I see no way to achieve that. Also: if you have any references to objects created by the delegate ClassLoaders, these objects will keep references to their ClassLoaders. I'm not sure there is a proper solution, but this may get you started.
这篇关于从类路径中动态删除jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!