I’d like to implement a method that takes an Object as argument, casts it to an arbitrary type, and if that fails returns null. Here’s what I have so far:
public static void main(String[] args) { MyClass a, b; a = Main.<MyClass>staticCast(new String('B')); } public static class MyClass { } public static <T> T staticCast(Object arg) { try { if (arg == null) return null; T result = (T) arg; return result; } catch (Throwable e) { return null; } }
Unfortunately the class cast exception is never thrown/caught in the body of the staticCast() function. It seems Java compiler generates the function String staticCast(Object arg) in which you have a line String result = (String) arg; even though I explicitly say that the template type should be MyClass. Any help? Thanks.
Because generic type information is erased at runtime, the standard way to cast to a generic type is with a
Classobject:Then call it like this: