简体   繁体   English

泛型类

[英]Casting in a Generic class

Below is the code snippet. 下面是代码片段。

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

My getValue method: 我的getValue方法:

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

When I create a object of the above class, like this: 当我创建上述类的对象时,如下所示:

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

... and make sure that store.getValue( operandType, operandId ) returns a string, I expect an error to occur in try block which is not happening. ...,并确保store.getValue( operandType, operandId )返回一个字符串,我希望try块中发生错误,但不会发生。 It's returning the string value instead. 它返回的是string值。

Any reason? 任何原因? Kindly explain. 请解释。 Thanks. 谢谢。

Do you simply invoke obj.evaluate() or do you invoke something like Integer x = obj.evaluate() 您只是调用obj.evaluate()还是调用类似Integer x = obj.evaluate()

For example: 例如:

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

This would fail with a ClassCastException , because it is there where Java realizes of the problem. 这将导致ClassCastException失败,因为Java在那里意识到了问题所在。

Before that it does not fail due to type erasure . 在此之前,它不会由于类型擦除而失败。 Basically, the type of T at runtime is simply java.lang.Object, and that's why a casting of anything to T seems to work, but once you attempt to use T in your call site you would get the exception when Java attempts to do a synthetic casting. 基本上,运行时T的类型只是java.lang.Object,这就是将任何内容强制转换为T似乎都起作用的原因,但是一旦您尝试在调用站点中使用T,您将在Java尝试执行此操作时得到异常。合成铸件。

Remove @SuppressWarnings( "unchecked" ) , and read the warning. 删除@SuppressWarnings( "unchecked" ) ,并阅读警告。

It tells you "Unchecked cast: 'java.lang.Object' to T". 它告诉您“未经检查的演员:'java.lang.Object'到T”。

Unchecked cast means: "the cast won't check that Object is an instance of T.". 未检查的强制类型转换意味着:“强制类型转换不会检查Object是T的实例。”。

So you've been warned by the compiler that this would not work, but ignored the warning. 因此,编译器已警告您这将行不通,但会忽略该警告。 It doesn't work due to type erasure. 由于类型擦除,它不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM