Reputation: 4469
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
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