Singleton类有几个不同的类加载器 [英] 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.
另外,如果我将实例设置为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));
}
这篇关于Singleton类有几个不同的类加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!