设计模式:Lazy Singleton,Generics和Inheritance:java.lang.Class无法强制转换为java.lang.reflect.ParameterizedType

时间:2013-01-06 08:44:52

标签: java generics inheritance singleton lazy-evaluation

我正在尝试使用泛型和继承来实现Lazy Singleton。我创建了一个abstract超类,并声明了一个Map,它将存储该类的子类的所有实例。

这是:

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

其中一个儿童班是:

public class ActivityTypeXMLParser extends AbstractXMLParser<ActivityTypeXMLParser>{
    private ActivityTypesXMLModel activityTypes;

    private ActivityTypeXMLParser() {

    }

    public static void main(String... strings) throws InstantiationException, IllegalAccessException {
        ActivityTypeXMLParser.getInstance();

    }
}

main方法用于测试目的。但我得到例外:

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)

现在调试后我发现了

Class<T> clazz = (Class<T>) ((ParameterizedType) AbstractXMLParser.class.getClass().getGenericSuperclass()).getActualTypeArguments()[0];

是异常的原因,因为AbstractXMLParser.class.getClass().getGenericSuperclass()正在返回class java.lang.Object。我需要在这里获得Class<T>。如何在课程AbstractXMLParserSingletonHolder的{​​{1}}中提取它?

3 个答案:

答案 0 :(得分:1)

此代码存在多个问题:

  • static方法不会被继承。 AbstractXMLParser.getInstance()ActivityTypeXMLParser被调用为ActivityTypeXMLParser.getInstance()时,AbstractXMLParser.class.getClass()无法知道它被调用。

  • Class' of会返回您班级的, not班级AbstractXMLParser<T>班级。

  • 目前尚不清楚为什么你需要T是通用的。请注意AbstractXMLParserSingletonHoldergetInstance()中的getInstance()是不同的类型参数。

您需要隐式地将有问题的类传递给getInstance(ActivityTypeXMLParser.class);

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends AbstractXMLParser> T getInstance(Class<T> clazz) 
    throws InstantiationException, 
    ...
}

{{1}}

答案 1 :(得分:1)

以下是我所做的完整解决方案,对某人有帮助。

abstract super-class

@SuppressWarnings({"all"})
public abstract class AbstractXMLParser<T> {    
    private static final Map<Class<? extends AbstractXMLParser>, AbstractXMLParser> INSTANCES = new HashMap<>();

    public AbstractXMLParser() {

    }

    private static class SingletonHolder<T> {               
        private static <T> T getInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
            Constructor<T> constructor = (Constructor<T>) clazz.getDeclaredConstructors()[0];
            constructor.setAccessible(true);            
            return constructor.newInstance(null);
        }
    }

    protected static <T extends AbstractXMLParser<T>> T getInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {      
        if(INSTANCES.containsKey(clazz)) {
            return (T) INSTANCES.get(clazz);
        } else {
            T instance = SingletonHolder.getInstance(clazz);
            INSTANCES.put(clazz, instance);
            return instance;
        }
    }

    protected static <T extends AbstractXMLParser<T>> void putInstance(Class<T> clazz, T instance) {
        if(!INSTANCES.containsKey(clazz)) {
            INSTANCES.put(clazz, instance);
        }
    }
}

其中一个孩子班:

public class ActivityTypeXMLParser extends AbstractXMLParser<ActivityTypeXMLParser>{

    private ActivityTypeXMLParser() {

    }   

    public static ActivityTypeXMLParser getInstance() {
        ActivityTypeXMLParser activityTypeXMLParser = null;

        try {
            activityTypeXMLParser = getInstance(ActivityTypeXMLParser.class);
        } catch (Exception exception) {
        }

        if(activityTypeXMLParser == null) {
            activityTypeXMLParser = new ActivityTypeXMLParser();
            putInstance(ActivityTypeXMLParser.class, activityTypeXMLParser);
        }

        return activityTypeXMLParser;
    }
}

答案 2 :(得分:0)

您似乎想要获取类的泛型类型,该类是抽象类的子类。但是你得到了

AbstractXMLParser.class.getClass()

这是抽象类的类,它始终是Class而是应该只使用getClass()到具体类的类。