java - 如何从通用静态工厂方法返回参数化派生类

标签 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);

最佳答案

你可以这样做:

// 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!

关于java - 如何从通用静态工厂方法返回参数化派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54433586/

相关文章:

Java 8 集合和流/forEach

java - 引用 Java 中的集合类型函数

scala - 具有类型成员的 Case 对象的模式匹配

在1.5上编译的java代码可以运行1.4环境

java - JButton 在使用 .setIcon(ICON) 时不会更改更新图像;

java - 如何创建使用相对路径生成文件的 evosuite 测试

java - CSVReader 无法正确读取一行

java - android 中的 BasicAuthentication for webview 不起作用

c - 解释 `_Generic`错误消息: error: invalid type argument of unary '` *`' (have '` int`')

java - 将引用类型作为参数传递并使用泛型