Java 中解决类型擦除的标准方法是将类标记传递给构造函数。例如,我们可以像这样定义一个通用属性类:
class Prop<T> {
public Prop(Class<T> type) {
this.type = type;
}
Class<T> type;
T t;
}
class IntProp extends Prop<Integer> {
public IntProp() {
super(Integer.class);
}
}
但是,如果我现在想使用另一个泛型类型参数(例如列表)并保留其泛型类型怎么办。我本来希望这样做:
class ListProp<J> extends Prop<ArrayList<J>> {
Class<J> subtype;
public ListProp(Class<J> type) {
super(ArrayList<J>.class);
subtype = type;
}
}
class IntListProp extends ListProp<Integer> {
public IntListProp() {
super(Integer.class);
}
}
但是当然super(ArrayList<J>.class)
不会编译,super(ArrayList.class)
. 解决这个问题的最佳方法是什么?