I am trying to implement Lazy Singleton with Generics and Inheritance. I have created a abstract
super-class and declared a Map which will store all the instances of the child class of this class.
Here it is:
public abstract class AbstractXMLParser<T> {
@SuppressWarnings("rawtypes")
private static final Map<Class<? extends AbstractXMLParser>, AbstractXMLParser> INSTANCES = new HashMap<>();
public AbstractXMLParser() {
throw new UnsupportedOperationException("Cannot instantiate");
}
private static class SingletonHolder<T> {
@SuppressWarnings({ "unchecked"})
private static <T> T getInstance() throws InstantiationException, IllegalAccessException {
Class<T> clazz = (Class<T>) ((ParameterizedType) SingletonHolder.class.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
return clazz.newInstance();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends AbstractXMLParser> T getInstance() throws InstantiationException, IllegalAccessException {
Class<T> clazz = (Class<T>) ((ParameterizedType) AbstractXMLParser.class.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
if(INSTANCES.containsKey(clazz)) {
return (T) INSTANCES.get(clazz);
} else {
T instance = SingletonHolder.getInstance();
INSTANCES.put(clazz, instance);
return instance;
}
}
}
And one of the child class is:
public class ActivityTypeXMLParser extends AbstractXMLParser<ActivityTypeXMLParser>{
private ActivityTypesXMLModel activityTypes;
private ActivityTypeXMLParser() {
}
public static void main(String... strings) throws InstantiationException, IllegalAccessException {
ActivityTypeXMLParser.getInstance();
}
}
The main
method is for testing purpose. But I am getting exception:
Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at com.edfx.adb.xml.parser.AbstractXMLParser.getInstance(AbstractXMLParser.java:25)
at com.edfx.adb.xml.parser.ActivityTypeXMLParser.main(ActivityTypeXMLParser.java:30)
Now after debugging I found that
Class<T> clazz = (Class<T>) ((ParameterizedType) AbstractXMLParser.class.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
is the reason for the exception, because AbstractXMLParser.class.getClass().getGenericSuperclass()
is returning class java.lang.Object
. I need to get the Class<T>
here. How can I extract it in the class AbstractXMLParser
and in SingletonHolder
of AbstractXMLParser
?
Copyright License:
Author:「Tapas Bose」,Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.
Link to:https://stackoverflow.com/questions/14180619/design-pattern-lazy-singleton-generics-and-inheritance-java-lang-class-cannot