类型擦除和收集

| 我在实现参数化的类Parameter时遇到一个特定的问题,但这是我在泛型之前遇到的,所以一般的解决方案会很好。 类Parameter的值是以下几种严格的类之一:
public class Parameter<T> {

/*
 * Specify what types of parameter are valid
 */
private static final Set<Class<?>> VALID_TYPES;
static {
    Set<Class<?>> set = new HashSet<Class<?>>();

    set.add( Integer.class );
    set.add( Float.class );
    set.add( Boolean.class );
    set.add( String.class );

    VALID_TYPES = Collections.unmodifiableSet(set);
}

private T value;

public Parameter(T initialValue) throws IllegalArgumentException {

    // Parameter validity check
    if (!VALID_TYPES.contains(initialValue.getClass())) {
        throw new IllegalArgumentException(
                initialValue.getClass() + \" is not a valid parameter type\");
    }

    value = initialValue;
}

    public T get() { return value; }

    public void set(T value) {
        this.value = value;
    }
}
一切都很好,直到我尝试将Parameter的实例存储在集合中。例如:
Parameter<Integer> p = new Parameter<Integer>(3); 
int value = (Integer)p.get();
p.set(2); // Fine

ArrayList<Parameter<?>> ps = new ArrayList<Parameter<?>>();
ps.add(p);
value = (Integer)(ps.get(0).get());

ps.get(0).set(4); // Does not compile due to type erasure
在这种情况下,其他人会怎么做才能避免这种情况? 谢谢     
已邀请:
好吧,您不能直接解决此问题。但是也许您还记得初始值的类?
class Parameter<T> {
    // ...
    private T value;
    private final Class<?> klass;

    public Parameter(T initialValue) throws IllegalArgumentException {
        if (!VALID_TYPES.contains(initialValue.getClass()))
            throw new IllegalArgumentException(...);
        value = initialValue;
        klass = initialValue.getClass();
    }

    @SuppressWarnings(\"unchecked\")
    public void set(Object value) {
        if (value != null && value.getClass() != klass)
            throw new IllegalArgumentException(...);
        this.value = (T)value;
    }
但是,您将丢失对set()的编译时类型检查。     
这不是类型擦除-您尝试为对象类型变量分配一个整数值。仅当参数类型为
Integer
时,此方法才有效,然后编译器知道必须装入整数。 尝试以下方法:     ps.get(0).set(new Integer(4)); 您可以立即执行的操作:完全删除
<?>
表达式。它将通过编译器警告替换编译器错误。一点都不出色,但可以编译。     

要回复问题请先登录注册