Don't lose to the unchecked warning! → After all, I couldn't win the unchecked warning ...

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

Don't lose to the unchecked warning! → After all, I couldn't win the unchecked warning ...
After all I wanted to preview the contents of mysql with Docker ...
I want to truncate after the decimal point
[Rails] I don't know how to use the model ...
I can't find the docker image after updating to docker desktop 2.4.0.0
After all, how should I attach the Constraint of ScrollView?
I think I understand the reuse of cells, but I don't understand at all.
What happened to the typical changes in Apache Wicket 8 after all?
I tried to explain the method
I was addicted to scrollview because I couldn't tap the variable size UIView