问题描述
我具有以下类层次结构:
public abstract class Config<T> implements Proxy<T> {
public abstract T parse();
public T get() {....}
}
public class IntegerConfig<Integer> extends Config<Integer> {
public Integer parse() {...}
}
public class LongConfig<Long> extends Config<Long> {
public Long parse() {...}
}
public class IntegerListConfig<List<Integer>> extends Config<List<Integer>> {
public List<Integer> parse() {....}
}
等等...
我想介绍一门新课:
public class ConfigMutation<T> implements Proxy<T> {
public ConfigMutation(....) {
//// create a concrete implementation of Config<T> according to actual parameterized type
}
}
本质上,我想避免重复Config的整个类层次结构,并在ConfigMutation中支持在Config类层次结构中具有参数化实现的所有类型。
无法找到一种方法。
(Class<T>)((ParameterizedType)getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0]
显然返回T,而不是实际类型。
此外,一旦解决了这个问题,如果有人可以建议使用泛型类型的工厂模式,我会很高兴,因此,当我在ConfigMutation中实例化Config派生类时,我就不必使用巨大的if来做到这一点。 ..else实际类型的代码块。
谢谢,Lior
1楼
将您的ConfigMutation
类更改为:
public class ConfigMutation<U,T extends Config<U>> implements Proxy<U> {
public ConfigMutation() {
}
}
然后,您可以将ConfigMutation
用作:
ConfigMutation<Integer,IntegerConfig> mutation;
您将无法执行以下所需的操作:
ConfigMutation<String,IntegerConfig> mutation;
就是说,您还需要对具体的Config
实现者进行更改。
例如,将IntegerConfig
更改为:
public class IntegerConfig extends Config<Integer> {
public Integer parse() {...}
}
该Integer
在IntegerConfig<Integer>
将被视为一种类型的参数,而不是Integer
类,这是不是你想要的。
(IDE应该为此警告您; 类型参数Integer隐藏了类型Integer )