The only place this is done is the enum classes that extend Enum. It uses a language twist and something like that class ClassA<T extends ClassA>. Or you do:
public class ClassA {
private static final Map<Class<? extends ClassA>, ClassA> singletons = new HashMap<>();
public static <T extends ClassA> T get(Class<T> klazz) {
T singleton = klazz.cast(singletons.get(klazz));
if (singleton == null) {
try {
singleton = klazz.getConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalArgumentException(e);
}
singletons.put(klazz, singleton);
}
return singleton;
}
protected ClassA() { }
}
Either you rethink your desire for plural singles and do a general search for containers (possibly with declarative XML or annotations) or in a bean container. EJB 3.1 is very nice and simple.
source
share