0

我在实现参数化类参数时遇到了一个特定问题,但这是我以前用泛型遇到过的问题,所以一个通用的解决方案会很好..

类参数存储严格数量的类之一的值:

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

在这种情况下,其他人会做什么来解决这个问题?

谢谢

4

2 回答 2

1

好吧,你不能直接解决这个问题。但也许你可以记住初始值的类?

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().. 的编译时类型检查。

于 2011-05-26T11:37:27.793 回答
0

这不是类型擦除 - 您尝试将整数值分配给对象类型变量。这仅参数类型为时有效Integer,然后编译器知道必须将整数收件箱。

试试这个:

ps.get(0).set(新整数(4));

可以立即执行的操作:<?>完全删除该表达式。它将用编译器警告替换编译器错误。一点也不出色,但可以编译。

于 2011-05-26T11:28:55.973 回答