2011-05-26 98 views
0

我有实施parametrised类参数特定的问题,但是这是我所遇到之前仿制药,所以一般的解决办法是好的..类型擦除和集合

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

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<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 

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

感谢

回答

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; 
    } 

然而,你将失去编译时间上设定的类型检查()..

0

这不是类型擦除 - 你试图将一个整数值分配给对象类型变量。如果参数类型为 Integer,那么只有 工作,那么编译器知道整数必须收件箱。

尝试此代替:

ps.get(0).SET(新的整数(4));

什么你可以马上做到:完全去除<?>表达。它将替换成编译器的错误通过编译器警告。根本没有辉煌,只能编译。

+0

实际上,该类型是不反对,但<捕获的?> ..无论如何,至少在我的编译器,new Integer(..)也不起作用。 – xs0 2011-05-26 11:39:19

+0

是的,在这里相同:类型Parameter 中的方法集(capture#2 of?)不适用于参数整数) – Ishmael82 2011-05-26 11:44:29

+0

是的,我明白了。还没有线索,*为什么*它不起作用。甚至在使用'<?时抱怨?扩展对象>'相反... – 2011-05-26 11:51:55