gpt4 book ai didi

java - Java中如何获取泛型接口(interface)实现的方法对象

转载 作者:行者123 更新时间:2023-12-01 17:21:02 25 4
gpt4 key购买 nike

就我而言,我想知道是否 apply Guava 给定实现的方法参数Function接口(interface)注释为@Nullable 。实现方法:

boolean isNullableArgument(Class<? extends Function<?,?>> function);

我不知道如何从 function 类中实现 apply 方法。

<小时/>

例如可能有像这样的 Function 实现:

new Function<String,Integer>() {
public Integer apply(String input) { … }
public Integer apply(Integer input) { … }
}

最佳答案

这是一个快速但肮脏的解决方案。不要直接复制并粘贴它 - 它只是作为一个示例来帮助您入门。

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

实际上,您需要分别对各种问题进行编码:

  • 在实现类型上查找通用接口(interface)
  • 查找F通用接口(interface)的类型参数
  • 查找apply实现
  • 检查给定注释的参数

正如代码中所指出的,这个解决方案很容易破坏更复杂的类型层次结构,例如:

abstract class LongFunction<T> implements Function<Long, T> { }

一个new LongFunction<String> { }将是 Function<Long, String>但上述方法不会定位通用 Function其运行时类型的接口(interface)。

关于java - Java中如何获取泛型接口(interface)实现的方法对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18753092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com