Jin Kwon
Jin Kwon

Reputation: 22025

call generic method from non generic method

I have two methods look like this. One is a generic method and the other is not.

<T> void a(final Class<T> type, final T instance) {
}
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)?
}

How can I call a() with type and instance from b()?

Upvotes: 2

Views: 374

Answers (2)

Paul Bellora
Paul Bellora

Reputation: 55233

Use a generic helper method:

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);
}

Class.cast will throw a ClassCastException if instance is not a T (so your earlier check may not be needed).

Upvotes: 5

subash
subash

Reputation: 3115

for example like this

a(String.class, new String("heloo"));

Upvotes: 0

Related Questions