2

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.

3
  • Can you show the OperandStore.getValue() method? In fact the class declaration too. Commented Aug 19, 2013 at 10:46
  • You need to show how you populate the HashMap in OperandStore? How did you actually create the OperandStore? It would be helpful, if you can post the class definition, with all the relevant methods being used here. Commented Aug 19, 2013 at 10:52
  • Show us how OperandStore class is implemented. Commented Aug 19, 2013 at 10:58

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.