JAVA8 之 Method References-Java in a Nutshell, 6th



JAVA8 的函数引用和 lambda表达式的关系=>函数引用是一种简化的 lambda表达式,只给出现有的函数,参数和返回值编译器推断去吧.java

 其实这语法和 lambda表达式正好相反, lambda表达式表示匿名方法,就是没有函数名,只给出参数和方法体.那么现有的函数就派上用场了,现有的函数有方法名,给出方法名,参数和方法体都已经有了,由编译器推断出.express

注:java中的方法不能独立存在,必须包含在类型中,这就是 lambda表达式 @FunctionalInterface的限制.ide

Recall that we can think of lambda expressions as methods that don’t have names.函数

Now, consider this lambda expression:this

// In real code this would probably be shorter because of type inferencespa

(MyObject myObj) -> myObj.toString()code

This will be autoconverted to an implementation of a @FunctionalInterface thatorm

has a single nondefault method that takes a single MyObject and returns String.编译器

However, this seems like excessive boilerplate, and so Java 8 provides a syntax forit

making this easier to read and write:

MyObject::toString

This is a shorthand, known as a method reference, that uses an existing method as a

lambda expression. It can be thought of as using an existing method, but ignoring

the name of the method, so it can be can used as a lambda, and autoconverted in the

usual way.

相关文章
相关标签/搜索