Why does using the cast
method on the Class<?>
Class produce an unchecked warning at compile time?
If you peek inside the cast method, you found this code :
public T cast(Object obj)
{
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj; // you can see there is a generic cast performed here
}
If i do a generic cast, the compiler complains saying that there is unchecked warning
.
Additional background information
You could find an example of how I arrived at this question inside the Book Effective Java 2 edition, page 166 (of the pdf).
The author writes this code
public <T> T getFavorite(Class<T> type)
{
return type.cast(favorites.get(type));
}
vs
public <T> T getFavorite(Class<T> type)
{
return (T) (favorites.get(type));
}
I just don't get the difference and why the compiler complains about the unchecked warning. In the end, both pieces of code do an explicit cast (T) object
, don't they?.