具有多个不同类加载器的单例类 [英] Singleton class with several different classloaders
问题描述
例如我有类 Singleton
和静态字段 instance
:
E.g I have class Singleton
with static field instance
:
public class Singleton {
private static Singleton instance;
// other code, construct, getters, no matter
}
我可以用两个不同的类加载器两次加载这个类.我怎么能避免呢?这是不安全和危险的.
I can load this class twice with two different classloaders. How could I avoid it? It is unsafe and dangerous.
另外,如果我将 instance 设置为 null,它是否会为两个类都设置为 null?
Also, if I set instance to null, would it set to null for both classes?
Singleton singleton = Singleton.getInstance();
singleton = null;
推荐答案
如果你想要一个真正的 Singleton
跨类加载器,那么你需要一个共同的父级来加载有问题的类,或者你需要自己指定类加载器.
If you want a true Singleton
across classloaders, then you need a common parent to load the class in question, or you need to specify the classloader yourself.
更新:下面来自@Pshemo 的评论,下面博客中的相当一部分内容可能直接来自 JavaWorld 文章.我已经留下了博客条目,因为它可能仍然对某人有帮助,但值得知道内容最初来自哪里.
Update: From the comment from @Pshemo below a fair bit of the content in the blog below might come directly from a JavaWorld Article. I've left the blog entry in as it may still help someone, but its worth knowing where the content originally came from.
原文:有一个 博客 条目为您提供了一种方法"(虽然我没试过!),而且看起来还算合理
Original: There is a blog entry that gives you a way to do this" (although I havent tried it!), and it looks fairly reasonable
根据下面的要求,我上面链接中的代码片段 - 我建议您访问博客以获取完整的上下文:
As requested below here a code snippet from my link above - I do suggest you visit the blog though for the full context:
private static Class getClass(String classname) throws ClassNotFoundException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if(classLoader == null)
classLoader = Singleton.class.getClassLoader();
return (classLoader.loadClass(classname));
}
这篇关于具有多个不同类加载器的单例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!