package com.sunstone.ref;import com.sunstone.lambda.Employee;import org.junit.Test;import java.io.PrintStream;import java.util.function.Consumer;import java.util.function.Supplier;publicclassTestMethodRef{@Testpublicvoidtest1(){
Consumer<String> con1 =(x)-> System.out.println(x);//@333@
con1.accept("hello");//@222@/*
public final class System {
* The "standard" output stream. This stream is already
* open and ready to accept output data. Typically this stream
* corresponds to display output or another output destination
* specified by the host environment or user.
* <p>
* For simple stand-alone Java applications, a typical way to write
* a line of output data is:
* <blockquote><pre>
* System.out.println(data)
* </pre></blockquote>
public final static PrintStream out = null;
...略
}
*/
PrintStream ps =System.out;
Consumer<String> con2 =(str)-> ps.println(str);//@333@
con2.accept("sun");//@222@//con1不太容易看出能否使用方法引用,con2则较为容易看出:// ->右侧的方法体已经有方法提供了实现(对象ps的实例方法println(str)),可以使用方法引用
Consumer<String> con3 = ps :: println;//@333@
con3.accept("stone");//@222@//换一种常见表达
Consumer<String> con4 = System.out :: println;//@333@
con4.accept("石头");//@222@//con4就是我们常用的表达形式//注意看下System.out对象的println方法的参数列表和返回值// 与 函数式接口Consumer的抽象方法accept方法的参数列表和返回值一致!/*
public class PrintStream extends FilterOutputStream
implements Appendable, Closeable{
* Prints a String and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>String</code> to be printed.
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
...略
}
*/}@Testpublicvoidtest2(){
Employee employee =newEmployee("雪豹",17,99999);
Supplier<Integer> sup1 =()-> employee.getAge();//@333@
System.out.println(sup1.get());//@222@
Supplier<Integer> sup2 = employee :: getAge;
System.out.println(sup2.get());}}
类名 :: 静态方法名
package com.sunstone.ref;import org.junit.Test;import java.util.Comparator;import java.util.function.BiFunction;publicclassTestMethodRef{@Testpublicvoidtest3(){
BiFunction<Double,Double,Double> biFunction1 =(x,y)-> Math.max(x,y);//@333@
System.out.println(biFunction1.apply(1.7,2.1));//@222@//Lambda表达式右侧的Lambda体,有静态方法已经提供了实现所以可以使用方法引用
BiFunction<Double,Double,Double> biFunction2 = Math :: max;//@333@
System.out.println(biFunction2.apply(1.7,2.1));//@222@/*
注意:方法引用中的静态方法max的参数列表和返回值 与 函数式接口biFunction1中的参数列表和返回值一致
public final class Math {
public static double max(double a, double b) {
if (a != a)
return a; // a is NaN
if ((a == 0.0d) &&
(b == 0.0d) &&
(Double.doubleToRawLongBits(a) == negativeZeroDoubleBits)) {
// Raw conversion ok since NaN can't map to -0.0.
return b;
}
return (a >= b) ? a : b;
}
...略
}
*/}@Testpublicvoidtest4(){
Comparator<Integer> comparator1 =(x,y)-> Integer.compare(x,y);
Comparator<Integer> comparator2 = Integer :: compare;}}