简体   繁体   中英

How to do instanceof and typecast with a generic type

In the following code I have two methods as_A and as_B , which basically do the same, but with different types A and B. How could I merge these two methods into one parametrized method? The approach shown in as_T doesn't work, because generic types are erased at runtime.

class A {}
class B extends A {}
class C extends A {}

B as_B(A a) {
    if (a instanceof B)
        return (B) a;
    else
        return null;
}

C as_C(A a) {
    if (a instanceof C)
        return (C) a;
    else
        return null;
}

<T extends A> T as_T(A a) {
    if (a instanceof T) // compile error because of type erasure
        return (T) a;
    else
        return null;
}

As you've said it yourself, T is erased, and the compiler prevents instanceof checks involving generic types or type parameters.

Depending on how you use your as_T method, you may be able to call it with a class instance corresponding to T , without compile-time warnings:

<T extends A> T as_T(A a, Class<T> type) {
    if (type.isInstance(a)) 
        return type.cast(a);
    else
        return null;
}

So that when you need a given subclass type, you call it with:

C c = as_T(a, C.class);
B b = as_T(a, B.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM