如何使用方法引用调用参数化方法

时间:2014-04-11 22:27:33

标签: java lambda java-8 method-reference

考虑下面的代码,

interface TestInter {
    public void abc();
}


class DemoStatic {

    public static void testStatic(String abc) {
        System.out.println(abc);
    }

    public void runTest () {

        // Using lambda expression.
        String str = "demo string" ;
        TestInter demo1 = () -> DemoStatic.testStatic(str);
        demo1.abc();

        // Using method reference.
        TestInter demo2 = DemoStatic::testStatic; // This line is not compiling.
        demo2.abc();
    }
}

我们可以调用testStatic方法作为TestInter接口abc()实现的主体,如果testStaic()方法的参数将被消除,如{{3}中所述}}

但在这种情况下,我们如何为参数化方法testStatic编写方法参考?

1 个答案:

答案 0 :(得分:10)

您的功能界面TestInter没有testStatic(String)方法的相应签名。如果您想使用testStatic()表示法引用::,则应添加参数:

interface TestInter2 {
    public void abc(String abc);
}

public void runTest () {
    TestInter2 demo2 = DemoStatic::testStatic;
    demo2.abc(str);
}

根据Oracle Java tutorial,有四种方法参考:

Four Types of Method Reference

我准备了3个接口 - 用于0,1和2参数。然后我们有3个静态和3个实例方法:

interface F0 {
    void f0();
}
interface F1 {
    void f1(MetRef i1);
}
interface F2 {
    void f2(MetRef i1, MetRef i2);
}

public class MetRef {
    public static void stat0() {;}
    public static void stat1(MetRef a) {;}
    public static void stat2(MetRef a, MetRef b) {;}

    public void inst0() {;}
    public void inst1(MetRef a) {;}
    public void inst2(MetRef a, MetRef b) {;}
}

现在看看每种方法如何在各种组合中用作方法参考,并将它们与前一个表进行比较。请参阅不同的方法参考类型,并注意参数的来源。

public class Test {
    public static void main(String[] args) {
        final MetRef mr = new MetRef();

        final F0 mr01 = MetRef::stat0; // 1: f0() ~ MetRef.stat0() 
        final F0 mr02 = mr::inst0;     // 2: f0() ~ mr.inst0()
        final F0 mr04 = MetRef::new;   // 4: f0() ~ new MetRef()

        final F1 mr11 = MetRef::stat1; // 1: f1(i1) ~ MetRef.stat1(i1)
        final F1 mr12 = mr::inst1;     // 2: f1(i1) ~ mr.inst1(i1)
        final F1 mr13 = MetRef::inst0; // 3: f1(i1) ~ i1.inst0()       <== NOTICE!

        final F2 mr21 = MetRef::stat2; // 1: f2(i1, i2) ~ MetRef.stat2(i1, i2)
        final F2 mr22 = mr::inst2;     // 2: f2(i1, i2) ~ mr.inst2(i1, i2)
        final F2 mr23 = MetRef::inst1; // 3: f2(i1, i2) ~ i1.inst1(i2) <== NOTICE!
    }
}