从非泛型方法调用泛型方法

Jin*_*won 2 java generics

我有两种方法看起来像这样.一种是通用方法,另一种不是.

<T> void a(final Class<T> type, final T instance) {
}
Run Code Online (Sandbox Code Playgroud)
void b(final Class<?> type, final Object instance) {

    if (!Objects.requireNotNull(type).isInstance(instance)) {
        throw new IllegalArgumentException(instance + " is not an instance of " + type);
    }

    // How can I call a(type, instance)?
}
Run Code Online (Sandbox Code Playgroud)

我怎么能说a()typeinstanceb()

Pau*_*ora 5

使用通用帮助方法:

void b(final Class<?> type, final Object instance) {

    if (!type.isInstance(instance)) {
        // throw exception
    }

    bHelper(type, instance);
}

private <T> void bHelper(final Class<T> type, final Object instance) {
    final T t = type.cast(instance);
    a(type, t);
}
Run Code Online (Sandbox Code Playgroud)

Class.cast将抛出ClassCastExceptionif instance不是a T(因此可能不需要您之前的检查).