Generics disappear at runtime, so a cast to T
is really just a cast to Object
(which the compiler will actually just get rid of), so there's no class cast exception.
abc
is just a method which takes an object and returns an object. StringBuilder.append(Object)
is the method which is called, as can be seen from the bytecode:
...
16: invokestatic #7 // Method abc:(Ljava/lang/Object;)Ljava/lang/Object;
19: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/Object;)Ljava/lang/StringBuilder;
...
When you do
String sss = (Test.abc(2)).toString();
Then the bytecode is
...
4: invokestatic #3 // Method abc:(Ljava/lang/Object;)Ljava/lang/Object;
7: checkcast #4 // class java/lang/Integer
10: invokevirtual #5 // Method java/lang/Integer.toString:()Ljava/lang/String;
...
Your code fails at the checkcast operation, which was not present before.