(Perhaps the complementary question to “How to create a generic singleton class in java?”🙂
class MyClass<T> {
private static Map<Class<MyClass<?>>, MyClass<?>> s_instances =
new HashMap<Class<MyClass<?>>, MyClass<?>>();
public static MyClass<?> blah(Class<MyClass<?>> clz)
throws InstantiationException, IllegalAccessException {
if (s_instances.get(clz) != null)
return s_instances.get(clz);
MyClass<?> instance = clz.newInstance();
s_instances.put(clz, instance);
return instance;
}
}
Is there a better idiom for having a singleton-per-type-argument-value?
Edit: Please do not answer merely to point out the lack of thread safety. Point taken. I’m asking whether I can do something more elegant than this map.
Please don’t do that.
A. Your singleton is not thread safe.
B. Be aware of double check pattern issues at Java.
C. Is it really that hard to have static initializer in each class and have:
and then
And if you really insist –
1. You can probably define a singleton that will manage types in a map to an instance (key is class or full class name, value is object)
2. You can add register your desired types there (I suggest they have private CTORs).
3. Use this answer in order to invoke the private CTOR , and create an instance to be placed in the value of the map entry.
4. Provide a getInstance method to the repoistory mentioned at 1, with the signature of:
This method will get the instance from the internal map.