(T) a is an uncontrolled execution: due to the erasure type , the runtime does not know what type T , so it cannot check if a belongs to type T
The compiler issues a warning when you do this; in your case, you suppressed this warning by writing @SuppressWarnings("unchecked") .
Edited to add (in response to the following question in the comments below):
If you want to check the roll, you can write this:
public class Test { public <T> void someGenericMethod(Class<T> clazz, Integer a) { T t = clazz.cast(a); System.out.println(t); System.out.println(t.getClass()); } public static void main(String[] args) { Test test = new Test();
by going to clazz , you let runtime check the broadcast; and, moreover, you allow the compiler to deduce T from the method arguments, so you no longer need to write test.<BigDecimal>someGenericMethod .
Of course, the code calling the method can still get around this using an unchecked listing:
public static void main(String[] args) { Test test = new Test(); Class clazz = Object.class; test.someGenericMethod((Class<BigDecimal>) clazz, 42); }
but then this is a main error, not someGenericMethod . someGenericMethod
ruakh source share