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 Class object:
public static <T> T staticCast(Object arg, Class<T> clazz) {
    if (arg == null) return null;
    if (!clazz.isInstance(arg))
        return null;
    T result = clazz.cast(arg);
    return result;
}
Then call it like this:
a = Main.staticCast("B", MyClass.class);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With