Java generics

I want to implement a method that takes object as a parameter, converts it to any type, and returns NULL if it fails This is 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, type cast exceptions are never thrown / caught in the body of the staticcast() function It seems that the java compiler generates the function string staticcast (object ARG), in which there is a line string result = (string) Arg; Even if I explicitly say that the template type should be MyClass Does it help? thank you.

Solution

Because the generic type information is erased at run time, the standard way to convert to a generic type is to use the 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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>