Skip to content
Advertisement

Java best practice for casting generics

I have the following code:

class ParametrizedObject<T> {...}
...
if (unknownObject instanceof ParametrizedObject) {
  ParametrizedObject casted = (ParametrizedObject) unknownObject;
}

This code triggers a rawtypes warning. Is there a way / best practice to avoid it ?

Note: The class ParametrizedObject is part of a framework, I can’t change it.

Advertisement

Answer

It really depends on what you are doing with the casted object, but if you don’t care about the type argument, a wildcard can be used to remove the warning:

if (unknownObject instanceof ParametrizedObject) {
    var casted = (ParametrizedObject<?>) unknownObject;
    ...
}

If you’re doing something like setting some internal state that relies on the type argument, then it’s not possible to safely do the cast due to type erasure, whereby all type parameters are replaced with Object:

class ParametrizedObject<T> {
    T data;

    void setData(T data) {
        this.data = data;
    }
}

MyClass someObject = ...;
ParametrizedObject<?> casted = (ParametrizedObject<?>) unknownObject;
casted.setData(someObject);  // won't compile

MyClass someObject = ...;
ParametrizedObject<MyClass> casted = (ParametrizedObject<MyClass>) unknownObject;
casted.setData(someObject); // compiles but above cast generates a warning
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement