ClassCastException during accessing methods of an generic class member
I am getting the runtime error Exception in thread "main" java.lang.ClassCastException: m.compiler.datatypes.Int cannot be cast to java.lang.Integer
Here are the code snippets:
public abstract class DataType<E> {
protected E value;
...
}
And here the class Int:
public class Int extends DataType<Integer> {
@Override
public DataType<Integer> compare(DataType<Integer> other) {
if(value > other.value) //here the exception is thrown
return new Int(1);
if (value < other.value开发者_如何学C)
return new Int(-1);
return new Int(0);
}
}
actual call:
if(lValue instanceof Int) {
Int lInt = (Int) lValue;
Int result = (Int) lInt.compare(rInt);
if i print the values inside compare the values are right, but even if i check with
other.value.getClass()
i get the exception. compiler has no error and no warnings.
At some point, you must have assigned an Int
to value
... And there should have been a warning about that. Can you make value
final
?
精彩评论