作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
就我而言,我想知道是否 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.");
}
实际上,您需要分别对各种问题进行编码:
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/
我是一名优秀的程序员,十分优秀!