When I try to cast in Java and write the following, I get an unchecked warning.
Object obj = new SomeClass();
SomeClass some = (SomeClass)obj;
To avoid this, there is a cast
method in the Class
class, so use this
Object obj = new SomeClass();
SomeClass some = SomeClass.class.cast(obj);
It seems that it should be done like this.
Then what happens in the next case?
Object obj1 = new Hoge<Fuga>();
Hoge<Fuga> some1 = (Hoge<Fuga>)obj1;
Object obj2 = new Hoge<Piyo>(); //Piyo is a subclass of Fuga
Hoge<? extends Fuga> some2 = (Hoge<? extends Fuga>)obj2;
Object obj3 = new Hoge<Moge>(); //Moge is Fuga's superclass
Hoge<? super Fuga> some3 = (Hoge<? super Fuga>)obj3;
In conclusion, it seems that the unchecked warning cannot be avoided for generic casts.
In the first place, in the case of Java, the type specified by generics is deleted at compile time, so it seems that it is not possible to properly judge and cast around that.
Even on Stackoverflow "What should I do?" "I can't. Give up and use @SuppressWarnings
" Is being exchanged.
As an aside, the implementation of the cast
method of the Class
class mentioned above is like this.
@SuppressWarnings("unchecked")
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj;
}
After all, you're using @SuppressWarnings ("unchecked ")
(anger)
So, it seems that you have to quietly add @SuppressWarnings ("unchecked ")
or create your own cast method like the cast
method of the Class
class just to avoid warnings.
Recommended Posts