带有泛型类型的Java 8方法引用 [英] Java 8 Method reference with generic types

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

问题描述

我遇到了Java 8方法引用与泛型类型相结合的问题。我简化了我的问题,明确了问题所在。以下代码失败:

  public static void main(String [] args){
new Mapper(TestEvent ::设置名称);
}

private static class Mapper< T> {
private BiConsumer< TestEvent,T>二传手;
private Mapper(BiConsumer< TestEvent,T> setter){this.setter = setter; }
}

private static class TestEvent {
public void setId(Long id){}
}

但是,如果我将构造函数调用改为

  BiConsumer< TestEvent,Long> consumer = TestEvent :: setId; 
新的Mapper(消费者);

一切正常。有人可以解释为什么吗?



我知道,如果我删除泛型类型(T)并使用Long,但在解决真正的问题时不起作用。

解决方案

目前您正在尝试使用 raw 映射器类型,该类型会擦除各种事物。

只要你开始使用泛型,一切都很好 - 类型推断可以帮助你:

 新的Mapper<>(TestEvent :: setId); 

添加<> all ,这是编译代码所需的。


I am having issues with Java 8 method reference combined with generic types. I have simplified my problem to make it clear where the problem lies. The following code fails:

public static void main(String[] args) {
    new Mapper(TestEvent::setId);
}

private static class Mapper<T> {
    private BiConsumer<TestEvent, T> setter;
    private Mapper(BiConsumer<TestEvent, T> setter) { this.setter = setter; }
}

private static class TestEvent {
    public void setId(Long id) { }
}

But if I change the constructor invocation to

    BiConsumer<TestEvent, Long> consumer = TestEvent::setId;
    new Mapper(consumer);

Everything works. Can someone explain why?

I know that it works if I remove the generic type (T) and use Long instead, but that will not work when solving my real problem.

解决方案

Currently you're trying to use the raw mapper type, which erases all kinds of things.

As soon as you start using the generic type, all is fine - and type inference can help you:

new Mapper<>(TestEvent::setId);

Adding <> is all that's required to make your code compile.

这篇关于带有泛型类型的Java 8方法引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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