2011-05-26 95 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