gpt4 book ai didi

java - 类型删除和集合

转载 作者:行者123 更新时间:2023-12-01 15:50:33 25 4
gpt4 key购买 nike

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

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

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

关于java - 类型删除和集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6137659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com