簡體   English   中英

泛型類

[英]Casting in a Generic class

下面是代碼片段。

public class Operand<T> {

    private OperandStore store;

    private final int operandType, operandId;

    public Operand( int operandType, int operandId, OperandStore store ) {
        this.operandId = operandId;
        this.operandType = operandType;
        this.store = store;
    }

    @SuppressWarnings( "unchecked" )
    public T evaluate() {
        try {
            return ( T ) store.getValue( operandType, operandId );
        }
        catch ( Exception e ) {
            return null;
        }
    }
}

我的getValue方法:

public Object getValue(int  operandType, int operandId ) {
      // return some value from a <String, Object> hashmap based on some condition
  }

當我創建上述類的對象時,如下所示:

Operand<Integer> obj = new Operand<>(1,1,store);

...,並確保store.getValue( operandType, operandId )返回一個字符串,我希望try塊中發生錯誤,但不會發生。 它返回的是string值。

任何原因? 請解釋。 謝謝。

您只是調用obj.evaluate()還是調用類似Integer x = obj.evaluate()

例如:

OperandStore store = new OperandStore();
Operand<Integer> obj = new Operand<>(1,1,store);
Integer x = obj.evaluate();

這將導致ClassCastException失敗,因為Java在那里意識到了問題所在。

在此之前,它不會由於類型擦除而失敗。 基本上,運行時T的類型只是java.lang.Object,這就是將任何內容強制轉換為T似乎都起作用的原因,但是一旦您嘗試在調用站點中使用T,您將在Java嘗試執行此操作時得到異常。合成鑄件。

刪除@SuppressWarnings( "unchecked" ) ,並閱讀警告。

它告訴您“未經檢查的演員:'java.lang.Object'到T”。

未檢查的強制類型轉換意味着:“強制類型轉換不會檢查Object是T的實例。”。

因此,編譯器已警告您這將行不通,但會忽略該警告。 由於類型擦除,它不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM