Reputation: 22025
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
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