如何从通用静态Factory方法返回参数化派生类

时间:2019-01-30 04:57:53

标签: java generics

我有这个静态工厂方法:

   public static CacheEvent getCacheEvent(Category category) {
        switch (category) {
            case Category1:
                return new Category1Event();
            default:
                throw new IllegalArgumentException("category!");
        }
    }

其中Category1Event定义为;

class Category1Event implements CacheEvent<Integer> ...

上述静态工厂方法的客户端代码如下:

   CacheEvent c1 = getCacheEvent(cat1);

编辑: 上面的代码工作正常。但是我更喜欢我不使用原始类型CacheEvent,而是使用参数化类型。使用上述原始类型的一个明显的缺点是,在以下情况下,我将不得不强制转换:

   Integer v = c1.getValue(); // ERROR: Incompatible types, Required String, Found Object. 

我可以如下进行未经检查的作业,但这会发出警告。我试图避免这种情况。

// Warning: Unchecked Assignment of CacheEvent to CacheEvent<Integer>. 
CacheEvent<Integer> c1 = getCacheEvent(cat1);

1 个答案:

答案 0 :(得分:2)

您可以这样做:

// Notice the <T> before the return type
// Add the type so the type for T will be determined
public static <T> CacheEvent<T> getCacheEvent(Category category, Class<T> type) {
    switch (category) {
        case Category1:
            return (CacheEvent<T>) new Category1Event(); // Casting happens here
        default:
            throw new IllegalArgumentException("Category: " + category);
    }
}

这样,在返回工厂返回的匹配实例类型时,将为类型参数T分配正确的类。

CacheEvent<Integer> cacheEvent = getCacheEvent(integerCategory, Integer.class);
int value = cacheEvent.getValue(); // no warnings!
相关问题