我们可以使用为java8的可选接口获取动态值的函数吗
我是Java8新手,尝试动态传递方法名以获取值 我有一个我们可以使用为java8的可选接口获取动态值的函数吗,java,reflection,lambda,java-8,optional,Java,Reflection,Lambda,Java 8,Optional,我是Java8新手,尝试动态传递方法名以获取值 我有一个请求请求,它有getInput1(),getInput2()方法。我可以静态映射可选,如下所示: void methodExecute(){ Optional<Request> request = Optional.of(new Request()); request.map(request::getInput1); //gives input1 value request.map(request::getInp
请求
请求,它有getInput1()
,getInput2()
方法。我可以静态映射可选,如下所示:
void methodExecute(){
Optional<Request> request = Optional.of(new Request());
request.map(request::getInput1); //gives input1 value
request.map(request::getInput2); //gives input2 value
}
static <T> Function<Request, T> reflect(String getterName, Class<T> resultType)
throws NoSuchMethodException, SecurityException {
Method method = Request.class.getMethod(getterName);
return req -> {
try {
return resultType.cast(method.invoke(req));
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
};
}
如果我理解正确,您的问题可以这样解决:
void methodExecute(){
Optional<Request> request = Optional.of(new Request());
request.map(request::getInput1); //gives input1 value
request.map(request::getInput2); //gives input2 value
}
static <T> Function<Request, T> reflect(String getterName, Class<T> resultType)
throws NoSuchMethodException, SecurityException {
Method method = Request.class.getMethod(getterName);
return req -> {
try {
return resultType.cast(method.invoke(req));
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
};
}
如果您希望动态地为getter生成函数
s,但不希望每次调用都诉诸反射,那么您可以使用与Java语言方法引用相同的后端:
static <T> Function<Request, T> reflect(String getterName, Class<T> resultType)
throws ReflectiveOperationException {
MethodHandles.Lookup l=MethodHandles.lookup();
MethodType getter=MethodType.methodType(resultType);
MethodHandle target = l.findVirtual(Request.class, getterName, getter);
getter=target.type();
try {
return (Function)LambdaMetafactory.metafactory(l, "apply",
MethodType.methodType(Function.class),
getter.generic(), target, getter).getTarget().invokeExact();
} catch(Throwable ex) {
throw new ReflectiveOperationException(ex);
}
}
静态函数反射(字符串getterName,类resultType)
抛出反射操作异常{
MethodHandles.Lookup l=MethodHandles.Lookup();
MethodType getter=MethodType.MethodType(resultType);
MethodHandle target=l.findVirtual(Request.class、getterName、getter);
getter=target.type();
试一试{
返回(函数)LambdaMetafactory.metafactory(l,“应用”,
MethodType.MethodType(Function.class),
getter.generic(),target,getter.getTarget().invokeExact();
}捕获(可丢弃的ex){
抛出新的ReflectOperationException(ex);
}
}
这可以使用与函数
调用相同的方法,但不会在调用上使用反射(通常;由于它是特定于JRE的,如果方法引用在特定JRE实现中也使用反射,则可能会使用反射)
但是,与反射方法一样,必须小心使用它,因为错误的使用不是在编译时发现的,而是在运行时发现的。我可以问一下我们该怎么做吗?如果它是一个具有多个参数(varags)(反射方法类型)的方法,那么它将如何使用LambdaMetaFactory doSomethig(字符串a、字符串b、int c)呢?有没有办法创建动态@functioninterface?@Saltuk评论部分不适合这样复杂的问题。只是一个新问题。别忘了包括你尝试过的和没有成功的细节。。这就是我想做的。。我希望你有时间。。非常感谢。