Java:如何解析泛型类型的lambda参数? [英] Java: how to resolve generic type of lambda parameter?
问题描述
好的,我们有 FunctionalInterface
:
Well, we have FunctionalInterface
:
public interface Consumer<T> {
void accept(T t);
}
我可以像这样使用它:
.handle(Integer p -> System.out.println(p * 2));
我们如何解析实际的泛型类型
在我们的代码中的lambda参数是什么?
How can we resolve the actual generic type
of that lambda parameter in our code?
当我们将它用作内联实现时,提取 Integer $并不困难c $ c>来自该类的方法。
When we use it as an inline implementation it isn't so difficult to extract the Integer
from the method of that class.
我错过任何东西吗?或者只是java不支持它的lambda类?
Do I miss anything? Or just java doesn't support it for lambda classes ?
为了更清洁:
lambda是用> MethodInvoker
(在上面提到的句柄
中),它在 execute(Message< ;? >消息)
为进一步的反射方法调用提取实际参数。在此之前,它使用Spring的 ConversionService
将提供的参数转换为目标参数。
That lambda is wrapped with MethodInvoker
(in the mentioned handle
), which in its execute(Message<?> message)
extracts actual parameters for further reflection method invocation. Before that it converts provided arguments to target params using Spring's ConversionService
.
方法 handle
在这种情况下是真正的应用程序工作之前的一些配置器。
The method handle
in this case is some configurer before the real application work.
不同的问题,但期望解决同一问题:< Java:使用lambda参数获取实际类型的泛型方法 a>
The different question, but with expectation for the solution for the same issue: Java: get actual type of generic method with lambda parameter
推荐答案
我最近添加了支持将lambda类型参数解析为 TypeTools 。例如:
I recently added support for resolving lambda type arguments to TypeTools. Ex:
MapFunction<String, Integer> fn = str -> Integer.valueOf(str);
Class<?>[] typeArgs = TypeResolver.resolveRawArguments(MapFunction.class, fn.getClass());
已解析的类型参数符合预期:
The resolved type args are as expected:
assert typeArgs[0] == String.class;
assert typeArgs[1] == Integer.class;
注意:底层实现使用由@danielbodart概述的ConstantPool方法,该方法已知可用于Oracle JDK和OpenJDK。
Note: The underlying implementation uses the ConstantPool approach outlined by @danielbodart which is known to work on Oracle JDK and OpenJDK.
这篇关于Java:如何解析泛型类型的lambda参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!