2

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.

simo
  • 33
  • 2
  • 1
    You can use `ParametrizedObject> casted = (ParametrizedObject>) unknownObject;` if it can be any type. – dan1st Mar 30 '21 at 15:21

1 Answers1

6

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
M A
  • 71,713
  • 13
  • 134
  • 174
  • 1
    Thanks, it works. Can you please elaborate, or give references to, other solutions that could be applicable depending on 'what i'm doing with the casted object' ? – simo Mar 30 '21 at 15:41
  • @simo I added an example that doesn't work when using wildcards, specifically when the generic type acts as a _consumer_ (see https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super as related). – M A Mar 30 '21 at 15:53
  • 1
    @simo - In addition to the link mentioned by M Anouti, you can also check https://stackoverflow.com/q/2776975/10819573 (which in turn points to the same link). – Arvind Kumar Avinash Mar 30 '21 at 16:40