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.
source
share