簡體   English   中英

自定義功能接口作為方法參數

[英]Custom functional interface as method argument

我有下面的代碼確實產生了預期的結果。 有人可以解釋窗簾背后發生了什么嗎? 我不明白編譯器/ JVM如何知道需要在Storer對象上調用store(String str)或者它如何定義doSomething(Storer s,String str)實現。

Storer.java

public class Storer {
    private List<String> storer = new ArrayList<>();

    public void store(String str) {
        storer.add(str);
    }

    @Override
    public String toString() {
        return "Storer [storer=" + storer + "]";
    }

}

MyInterface.java

@FunctionalInterface
public interface MyInterface {
    public abstract void doSomething(Storer s, String str);
}

Executor.java

public class Executor {
    public void doStore(Storer storer, String s, MyInterface p) {
        p.doSomething(storer, s);
    }
}

TestFunctionalInterfaces.java

public class TestFunctionalInterfaces {
    public static void main(String[] args) {
        Storer storer = new Storer();

        Executor test = new Executor();
        test.doStore(storer, "I've got added", Storer::store);

        System.out.println(storer);
    }
}

輸出是:

Storer [storer=[I've got added]]

提前致謝。

Storer::store是一個方法引用,可用於代替任何@FunctionalInterface 你在這里得到的基本上是My Interface實現的簡寫。 相當於:

public class MyInterfaceImpl implements MyInterface {
    public void doSomething(Storer storer, String str) {
       storer.store(str);
    } 
}

這個實現(通過你的方法引用指定)是執行storer.store()的原因...因為你已經指定並傳遞給你的Executor的MyInterface的實現。 編譯器足夠智能,可以將實現/方法引用與您提供的參數相匹配

方法引用Store::storer等效於lambda (s, str) -> s.store(str) 通常,給定一個期望args a1,a2,a3,...的函數接口,此類型的方法引用等效於調用a1.namedMethod(a2,a3,...)的lambda。 看到這個答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM