Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics

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.

like image 698
Budric Avatar asked Mar 11 '09 17:03

Budric


1 Answers

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);
like image 124
Michael Myers Avatar answered Nov 14 '22 20:11

Michael Myers