下面是代碼片段。在通用類中鑄造
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
的值。
任何理由?請解釋一下。謝謝。
你可以顯示'OperandStore.getValue()'方法嗎?實際上也是類聲明。 –
更新了代碼。這會有幫助嗎?謝謝。 – LPD
你需要展示如何在OperandStore中填充'HashMap'?你是如何創建「OperandStore」的?如果您可以發佈類定義,並且在此使用所有相關的方法,這將會很有幫助。 –