【问题标题】:How can I return parameterized derived classes from a generic static Factory Method [duplicate]如何从通用静态工厂方法返回参数化派生类 [重复]
【发布时间】:2019-06-23 07:41:36
【问题描述】:

我有这个静态工厂方法:

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

【问题讨论】:

  • 你得到什么错误?
  • 我从那个方向开始,但不确定如何使用那个 typeToken。你能举个例子吗?

标签: java generics


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 感谢@KaNa0011,我实际上编写了该代码,但后来意识到我需要在 getCacheEvent 方法中进行未经检查的强制转换。所以如果没有未经检查的演员表,似乎没有任何办法解决这个问题?
猜你喜欢
  • 2012-05-13
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 2012-05-24
  • 2021-07-26
  • 1970-01-01
  • 2010-10-10
  • 2016-11-14
相关资源
最近更新 更多