首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型擦除和集合

类型擦除和集合
EN

Stack Overflow用户
提问于 2011-05-26 19:21:09
回答 1查看 237关注 0票数 0

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

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

代码语言:javascript
复制
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的实例存储在一个集合中。例如:

代码语言:javascript
复制
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

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

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-05-26 19:37:28

嗯,你不能直接解决这个问题..但也许你能记住初始值的类?

代码语言:javascript
复制
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()上丢失编译时类型检查。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6137659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档