WeiChing 林煒清
WeiChing 林煒清

Reputation: 4469

a little about generic casting in java

In Java,everybody know Integer cannot be cast to String, which is an error at compile time.

Now for this generic case,

        public <T> T cast(Object o) {
            return (T) Integer.class.cast(o);//cast Integer to T
        }

        void method1() {
            String q = cast("q"); //T is String
        }

I just don't understand why in this case java can not warn you at compile time where Integer is cast to String. Why that? In my knowleages,the type erasure is happened after compiling.

Edit:I just thought that the compiler has type inference to know that T is String, so that Integer cannot be cast to. But apparently it dosen't.

Upvotes: 2

Views: 1385

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280168

With this

public <T> T cast(Object o) {
     return (T) Integer.class.cast(o);//cast Integer to T
}

you declare a type variable T that is unbounded, ie. it can be any reference type. So the cast to Integer might work or it might not.

All the compiler can do is warn you

Type safety: Unchecked cast from Integer to T

If, instead, you had given bounds to the type variable, something like

public <T extends CharSequence> T cast(Object o) {
    return (T) Integer.class.cast(o); // Cannot cast from Integer to T
}

then you would very much get a compilation error because CharSequence and Integer are not in the same inheritance hierarchy and are therefore incompatible.

In this specific case, you would get the compilation error even without the cast to T. This is because

AnyTypeName.class 

always returns a Class<ThatTypeName> and Class#cast makes use of the generic type. In this case it would return an Integer and Integer is not convertible to T.

Upvotes: 5

Related Questions