我在实现参数化类参数时遇到了一个特定的问题,但这是我以前在泛型中遇到的问题,所以一般的解决方案会很好。
class参数存储严格数量的类之一的值:
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在这种情况下,其他人会做些什么来解决这个问题呢?
谢谢
发布于 2011-05-26 19:37:28
嗯,你不能直接解决这个问题..但也许你能记住初始值的类?
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()上丢失编译时类型检查。
https://stackoverflow.com/questions/6137659
复制相似问题