Casting with type parameters in java
Let's say I have a class like this:
class ParameterizedType<T>{
public boolean equals(Object o){
if (ParameterizedType<T>.class.isInstance(o)){
ParameterizedType<T> other = (ParameterizedType<T>) o;
return this.toString() == other.toString();
}
return false;
}
}
I can get two different warnings from eclipse in a method like this.
-
ParameterizedType<T>.class
is not syntactically correct -
(ParameterizedType<T>)
o is an untested cast
How can you get around this?
source to share
-
ParameterizedType<T>.class
is not syntactically correct
The reason for this is that when .class
you are referencing a value .class
in Runtime, and since Generics is a Java compile-time function and type parameters are erased and replaced with actual types, this statement does not make sense in Runtime, but is <T>
completely redundant.
Note that this rule applies to the operator instanceof
(i.e. you cannot do if (something instanceof SomeGenericClass<T>)
)
-
(ParameterizedType<T>)
o is an unverified listing
Cannot be compared Object
to ParameterizedType
unless dumped down. The IDE correctly indicates that the cast is unchecked, but to compare instances you have to drop at some point. In this case, adding a @SuppressWarnings("unchecked")
above the method will be fine.
Also note that Strings in Java should not be compared to==
source to share