我在实现参数化类参数时遇到了一个特定问题,但这是我以前用泛型遇到过的问题,所以一个通用的解决方案会很好..
类参数存储严格数量的类之一的值:
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
在这种情况下,其他人会做什么来解决这个问题?
谢谢