java lamda 参数,Java:如何解析泛型类型的lambda参数?

Well, we have FunctionalInterface:

public interface Consumer {

void accept(T t);

}

And I can use it like:

.handle(Integer p -> System.out.println(p * 2));

How can we resolve the actual generic type of that lambda parameter in our code?

When we use it as an inline implementation it isn't so difficult to extract the Integer from the method of that class.

Do I miss anything? Or just java doesn't support it for lambda classes ?

To be more cleaner:

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.

The method handle in this case is some configurer before the real application work.

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

解决方案

I recently added support for resolving lambda type arguments to TypeTools. Ex:

MapFunction 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;

Note: The underlying implementation uses the ConstantPool approach outlined by @danielbodart which is known to work on Oracle JDK and OpenJDK.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值