There will be no ClassCastException exceptions when your T has some base:
public class GenericsTest { public static void main(String[] args) { System.out.println(cast(Integer.valueOf(0))); System.out.println(GenericsTest.<Long> cast(Integer.valueOf(0))); System.out.println(GenericsTest.<Long> cast("Hallo")); System.out.println(castBaseNumber(Integer.valueOf(0))); System.out.println(GenericsTest.<Long> castBaseNumber(Integer.valueOf(0))); System.out.println(GenericsTest.<Long> castBaseNumber("Hallo")); } private static <T extends Number> T castBaseNumber(Object o) { T t = (T)o; return t; } private static <T> T cast(Object o) { T t = (T)o; return t; } }
In the above example, there will be no ClassCastException in the first 5 calls to cast and castBaseNumber. Only the 6th call throws a ClassCastException, because the compiler efficiently translates cast () to return (Object) o; and castBaseNumber () to return (Number) o ;. Wenn you write
String s = GenericsTest.<Long> cast("Hallo");
You will get a ClassCastException, but not in the cast-method, but when you assign s.
So I really think that your T is not just T, but T is expanding something. So you can check:
Object o = decoder.readObject(); if (o instanceof Something) restoredItem = (T) o; else
But this will still result in an error later when you use your class.
public Reader<T extends Number>{...} Long l = new Reader<Long>("file.xml").getValue();
In this case, only Tom advise can help.
Tobias schulte
source share