Java 8中有代表吗? [英] Are there delegates in Java 8?

查看:134
本文介绍了Java 8中有代表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果没有,我们如何在没有代理的JDK 8中使用lambda表达式?

>

什么是方法参考?他们和代表一样吗?

解决方案

JDK 8中没有任何代表。在引导下,lambdas是功能界面的实例一个接口,一个抽象方法)。根据您传递lambda的位置,编译器可以确定其实现的接口。例如,Collections.sort方法接受一个Comparator实例作为第二个参数。比较器恰好是一个功能界面,因此编译器将检查您所传递的lambda是否与Comparator中的抽象方法匹配。



方法引用只是一个简化。当你的lambda只是调用一个现有的方法,你可以使用这个新的语法来简化结构。
来自链接教程的示例显示得很好:



而不是:

  Arrays.sort(rosterAsArray,
(a,b) - > Person.compareByAge(a,b)
);

方法参考更简单:

  Arrays.sort(rosterAsArray,Person :: compareByAge); 

看看 lambdafaq


Are there delegates in Java 8?

If not, how do we have lambda expressions in JDK 8 without delegates?

What are method references? Are they the same as delegates?

解决方案

There are no delegates in JDK 8. Under the hood lambdas are instances of functional interfaces (an interface with exactly one abstract method). Depending on where you are passing your lambda the compiler can figure out what interface it is implementing. For example the Collections.sort method accepts a Comparator instance as a second parameter. The Comparator happens to be a functional interface so the compiler will check if the lambda you are passing matches the abstract method in Comparator or not.

A Method reference is just a simplification. When your lambda is just calling an existing method you can use this new syntax to simplify the construct. The example from the linked tutorial shows it pretty well:

instead of:

Arrays.sort(rosterAsArray,
    (a, b) -> Person.compareByAge(a, b)
);

it's simpler with method reference:

Arrays.sort(rosterAsArray, Person::compareByAge);

Have a look on the lambdafaq.

这篇关于Java 8中有代表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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