" Why does using a method castin a class Classgenerate an unchecke...">

Java - Generics - Explicit casting and casting method of class "Class <?>"

Why does using a method castin a class Class<?>generate an unchecked warning at compile time?

If you look inside the casting method, you have 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 generic copying, the compiler complains that it exists unchecked warning.


Additional reference information

You can find an example of how I came to this issue in the editors of Book Effective Java 2, p. 166 (from pdf).

The author writes this code

public <T> T getFavorite(Class<T> type) 
{
    return type.cast(favorites.get(type));
}

against

public <T> T getFavorite(Class<T> type) 
{
    return (T) (favorites.get(type));
}

I just don't understand why the compiler complains about an unverified warning. After all, both parts of the code do an explicit listing (T) object, right ?.

+4
2

@SuppressWarnings("unchecked") java.lang.Class . , JDK , . , JDK .

@Bohemian , " ", , , . ( java.lang.Enum#getDeclaringClass.) , , , , .

- : , java.lang.Class#cast .

+7

, Java , ( ). cast , .. :

Object o = new Integer(42);
String s = (String) o;  // compiles, but throws ClassCastException at runtime

, cast ClassCastException, .

Java, . , , , , .

( , ), ( , , , , ). :

class C<T> {
    final T field;

    C(Object o) {
        this.field = (T) o; // unchecked. Will never throw a ClassCastException.
    }
}

boolean test() {
    C<String> c = new C<String>(42);
    return c.field.startsWith("hello"); // throws ClassCastException, even though there is no cast in the source code at this line!
}

, .

, ( Class.cast()) , :

public T cast(Object obj) 
{
    if (obj != null && !isInstance(obj))
        throw new ClassCastException(cannotCastMsg(obj));
    return (T) obj;
}

- , , .

+1

Source: https://habr.com/ru/post/1541990/


All Articles