简体   繁体   中英

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:

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. It's returning the string value instead.

Any reason? Kindly explain. Thanks.

Do you simply invoke obj.evaluate() or do you invoke something like 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.

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.

Remove @SuppressWarnings( "unchecked" ) , and read the warning.

It tells you "Unchecked cast: 'java.lang.Object' to T".

Unchecked cast means: "the cast won't check that Object is an instance of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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