Java 如何从泛型静态工厂方法返回参数化派生类

Java 如何从泛型静态工厂方法返回参数化派生类,java,generics,Java,Generics,我有一个静态工厂方法: public static CacheEvent getCacheEvent(Category category) { switch (category) { case Category1: return new Category1Event(); default: throw new IllegalArgumentException("c

我有一个静态工厂方法:

   public static CacheEvent getCacheEvent(Category category) {
        switch (category) {
            case Category1:
                return new Category1Event();
            default:
                throw new IllegalArgumentException("category!");
        }
    }
其中类别1事件定义为:

class Category1Event implements CacheEvent<Integer> ...
编辑: 上面的代码运行良好。但是,我不希望使用原始类型
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);

//警告:未选中CacheEvent到CacheEvent的分配。
CacheEvent 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);
    }
}

你犯了什么错误?我是从那个方向开始的,但不知道如何使用typeToken。你能提供一个例子吗?谢谢@KaNa0011,我实际上写了这段代码,但后来意识到我需要在getCacheEvent方法中使用unchecked强制转换。因此,如果没有未经检查的强制转换,似乎没有任何方法可以解决此问题?
// 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);
    }
}
CacheEvent<Integer> cacheEvent = getCacheEvent(integerCategory, Integer.class);
int value = cacheEvent.getValue(); // no warnings!