[英]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()
? 我怎么能叫
a()
与type
和instance
从b()
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). 如果
instance
不是T
则Class.cast
将抛出ClassCastException
(因此可能不需要您进行早期检查)。
例如这样
a(String.class, new String("heloo"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.