George
George

Reputation: 7543

Cast java Object to a generic type with a known type parameter

I have a generic class like this:

public class Box<T> {
   ...
}

Later in code I want to cast an Object to the Box class this way:

Box<String> boxString = (Box<String>) object;

But the compiler and the IDE issue a warning here.
Can I avoid the warning somehow cleanly by not using @SuppressWarnings?

Upvotes: 2

Views: 259

Answers (2)

Andy Thomas
Andy Thomas

Reputation: 86381

The warning is a good thing. It's telling you that the type parameters part of the cast are not going to be type-checked at run-time. If you know for certain that it's always going to be a valid cast, it's reasonable to use @SuppressWarnings("unchecked").

However, avoiding warnings is better than the suppressing them.

If you control the construction of the Box instances that you later need to cast, you can subclass Box, since it's not final.

 public class BoxString extends Box<String> { 
     ...
 }

Now you can cast without generics:

 if ( object instanceof BoxString ) {
    BoxString boxString = (BoxString) object;
    ...
 }

Upvotes: 1

Ga&#235;l J
Ga&#235;l J

Reputation: 15050

If the type of object is Object, then you cannot avoid the warning other than by adding @SuppressWarnings("unchecked").

Warnings are not errors, you can have some in your code if you understand them.

EDIT : as suggested from comment, added "unchecked" to the annotation.

Upvotes: 3

Related Questions