Java:如何解析泛型类型的lambda参数? [英] Java: how to resolve generic type of lambda parameter?

查看:1256
本文介绍了Java:如何解析泛型类型的lambda参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我们有 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 来自该类的方法。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆