Это быстрое и грязное решение. Не копируйте и не вставляйте его напрямую - это только пример, чтобы вы начали.
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> { }
new LongFunction<String> { }
бы Function<Long, String>
, но вышеупомянутый метод будет не место общего Function
интерфейса на его тип времени выполнения.
Я не думаю, что возможная реализация функции, которую вы описываете, на самом деле была бы законной. Ты это пробовал? –
@LouisWasserman Я нашел решение. –