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

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

问题描述

好吧,我们有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(在提到的 handle 中)包裹,它在它的 execute(Message 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 参数获取泛型方法的实际类型

The different question, but with expectation for the solution for the same issue: Java: get actual type of generic method with lambda parameter

推荐答案

我最近添加了对解析 lambda 类型参数的支持到 类型工具.例如:

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天全站免登陆