How to create a singleton class
As per the comment on your question:
I've a properties file containing some keys value pairs, which is need across the application, that is why I was thinking about a singleton class. This class will load the properties from a file and keep it and you can use it from anywhere in the application
Don't use a singleton. You apparently don't need one-time lazy initialization (that's where a singleton is all about). You want one-time direct initialization. Just make it static and load it in a static initializer.
E.g.
public class Config {
private static final Properties PROPERTIES = new Properties();
static {
try {
PROPERTIES.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
} catch (IOException e) {
throw new ExceptionInInitializerError("Loading config file failed.", e);
}
}
public static String getProperty(String key) {
return PROPERTIES.getProperty(key);
}
// ...
}
If you are using reflection to pierce encapsulation, you should not be surprised when behavior of your class is altered in incorrect ways. Private members are supposed to be private to the class. By using reflection to access them you are intentionally breaking the behavior of the class, and the resultant "duplicate singleton" is expected.
In short: Don't do that.
Also, you might consider creating the singleton instance in a static constructor. Static constructors are synchronized and will only run once. Your current class contains a race condition -- if two separate threads call getInstance()
when it has not been previously called, there is a possibility that two instances will be created, one of them being exclusive to one of the threads, and the other becoming the instance that future getInstance()
calls will return.