Your translation method performs an unchecked conversion that is specifically used by the JVM to provide backward compatibility with non-generic code.
Such calls cannot be shown as statically safe in the generic type system. Rejecting such calls will invalidate the large bodies of the existing code and prevent them from using newer versions of the libraries. JLS 5.1.9
A method call without explicit type parameters will cause the compiler to output a parameter of type invocations, in this case, based on their expected return type. Output Type , JLS 12.15.2.7. . This means that the code is equivalent to this:
String foo = Caster.<String>cast("hi");
Primitive types will be displayed in their version box:
If A is a primitive type, then A is converted to a reference type U by means of a box conversion, and this algorithm is applied recursively to the constraint U <F. JLS 12.15.2.7.
The JVM provides type safety by performing runtime type checks for return values โโof functions containing uncontrolled casts, at the first point where the type information is not erased (I did not find it explicitly specified in the specification, but it looks like this: work this way, although this mentioned in Java Tutorials ). In this case, when you try to assign a value to a typed local variable, the type of the return value is checked, resulting in a ClassCastException .
To give more detailed information about when a forced execution check is performed at run time, consider a few more examples:
Object a3 = Caster.<String>cast(3);
EDIT:
Here is the StackOverflow question about when runtime type checks are performed: When is the total return value of a function different after deleting styles?
Tamas hegedus
source share