Why does this generic throw fail?

I expect this code to throw a ClassCastException:

public class Generics {
    public static void main(String[] args) {
        method(Integer.class);
    }

    public static <T> T method(Class<T> t) {
        return (T) new String();
    }
}

But this is not so. Casting String to T is not interrupted until I use the returned object in some way, for example:

public class Generics {
    public static void main(String[] args) {
        method(Integer.class).intValue();
    }

    public static <T> T method(Class<T> t) {
        return (T) new String();
    }
}

Reference Information. I created a class that uses JAXB to untie the XML file. It looks like this:

public static <T> T unmarshal(File file, Class<? extends T> clazz)

Depending on whether the root-Element is an anonymous type or not, T or JAXBElement is returned. JAXBElement, of course, cannot be attributed to T. In my unit test, where I called unmarshal (), without doing anything with the result, everything worked fine. In the code this failed.

Why doesn't it work directly? This is mistake? If not, I would like to understand why.

+5
source share
3

, T .

, ,

public class Generics {

    public static void main(String[] args) {
        Generics.method(Integer.class).intValue();
    }

    public static Object method(Class<Object> t) {
        return (Object) new String();
    }
}

:

public class Generics {

    public static void main(String[] args) {
        Generics.<Integer>method(Integer.class).intValue();
    }

    public static <T> T method(Class<T> t) {
        return (T) new String();
    }
}

.

+4

T , Object. , String ...

+4

I think you can make a stronger method definition like this:

public static <T extends Number> T method(Class<T> t) {
    return //// some code.
}

In this case, the string return new String () simply cannot be compiled.

but the string returns a new Integer (123); compiled, works and does not require casting.

+1
source

All Articles