java中双冒号是什么

有时候看到有一些java代码中会有一个类::方法这样的写法,这种写法叫做方法引用,常用的几种写法如下:

 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
 * 1. 实例方法引用object::methodName
 * 2. 构造方法引用className::new
 * 3. 基于参数实例方法引用className::methodName
 * 4. 静态方法应用className::staticMethodName
 */
public class Java8Test {
    public String method(String s) {
        System.out.println(s);
        return s + "dddd";
    }

    public interface Compare {
        int do(String n, String v);
    }

    public interface TestGet {
        String get();
    }

    public interface TestCC {
        String do(Java8Test n, String v);
    }

    @Test
    public void one() {
        // 实例方法引用
        Java8Test cc = new Java8Test();
        Function<String, String> d = cc::method;
        System.out.println(d.apply("ddd"));

        System.out.println(((Function<String, String>) cc::method).apply("ccc"));

        // 基于参数实例方法引用
        Compare c = String::compareTo;
        System.out.println(c.do("1", "2"));

        // 基于参数实例方法引用(根据参数类型自动推导)
        TestCC sdf = Java8Test::method;
        sdf.do(new Java8Test(), "test::method");

        // 构造方法引用
        TestGet f = String::new;
        System.out.println(f.get());

        // Supplier
        Supplier<String> t = String::new;
        System.out.println(t.get());

        // 静态引用
        Function<String, Integer> dd = Integer::valueOf;
        System.out.println(dd.apply("3"));

        System.out.println(((Function<String, Integer>) Integer::valueOf).apply("3"));
    }
}