java8之方法引用

来源:互联网 发布:网络挖掘机程式 编辑:程序博客网 时间:2024/05/21 19:27
 XML Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.lyzx.day02;

import org.junit.Test;


public class T5{
    
    
    /**
     * 方法引用
     * 当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
     * (实现抽象方法的参数列表,必须与方法引用方法的参数列表保持一致!)
     * 方法引用:使用操作符 "::" 将方法名和对象或类的名字分隔开来。
     * 如下三种主要使用情况:
     * 对象::实例方法
     * 类::静态方法
     * 类::实例方法
     */
    @Test
    public void test1(){
        //加入Calculate的calc方法是求两个数中大的,而Math的max方法正好是这个功能
        //所以可以使用Math::max 即类::静态方法名
        Calculate c = Math::max;
        int max = c.calc(9,900);
        System.out.println(max);
    }
}

@FunctionalInterface
interface Calculate{
    public int calc(int a,int b);
}

@FunctionalInterface
interface Str{
    public String toUpper(String str);
}
原创粉丝点击