这是一个快速而肮脏的解决方案。不要直接复制和粘贴它——它只是作为一个例子来帮助你入门。
static boolean applyHasAnnotation(
@SuppressWarnings("rawtypes") final Class<? extends Function> functionType,
final Class<? extends Annotation> annotationType
) throws SecurityException, NoSuchMethodException {
//for each directly implemented interface,
for (final Type interfaceType : functionType.getGenericInterfaces()) {
//if the interface is parameterized,
if (interfaceType instanceof ParameterizedType) {
final ParameterizedType genericInterfaceType = (ParameterizedType)interfaceType;
//if the interface is Function
if (genericInterfaceType.getRawType() == Function.class) {
//get the type argument for T
final Type inputType = genericInterfaceType.getActualTypeArguments()[0];
//get its raw type
final Class<?> rawInputType =
(inputType instanceof ParameterizedType)
? (Class<?>)((ParameterizedType)inputType).getRawType()
: (Class<?>)inputType;
//use it to find the apply implementation
final Method applyMethod = functionType.getDeclaredMethod("apply", rawInputType);
//for each annotation on its first (and only) parameter,
for (final Annotation inputAnnotation : applyMethod.getParameterAnnotations()[0]) {
//if its type is the specified annotation type, return true
if (inputAnnotation.annotationType() == annotationType) {
return true;
}
}
return false;
}
}
}
//a more complicated inheritance hierarchy has defeated us
throw new IllegalArgumentException("Function info not found.");
}
实际上,您需要分别对各种问题进行编码:
- 在实现类型上找到泛型接口
- 查找
F
泛型接口的类型参数
- 查找
apply
实施
- 检查给定注释的参数
正如代码中所指出的,对于更复杂的类型层次结构,此解决方案很容易中断,例如:
abstract class LongFunction<T> implements Function<Long, T> { }
Anew LongFunction<String> { }
将是 aFunction<Long, String>
但上述方法不会将泛型Function
接口定位在其运行时类型上。