下面是代码片段。
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
block 中会发生错误,但实际上并没有发生。它返回 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 意识到问题的地方。
在此之前它不会因 type erasure 而失败.基本上,运行时 T 的类型就是简单的 java.lang.Object,这就是为什么将任何东西转换为 T 似乎都有效的原因,但是一旦您尝试在调用站点中使用 T,当 Java 尝试执行此操作时就会出现异常合成铸件。
关于java - 在通用类中转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18311873/