Singleton class with several different classloaders

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.

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

Leave a Comment