我想了解Java 8中的lambdas。我有一個使用功能接口的非常簡單的示例。使用java 8傳遞函數代碼供應商
這不是一個工作例子,我知道我可以直接調用method1
和method2
,而不是使用getValue()
和Supplier
,但是,我想知道是否有使用supplier.get()
調用method1
和method2
任何問題。
public <T> T mytest(SomeObject var) {
//extract values from someobject
if(somecondition) {
getValue(() -> method2(obj5instance, obj6instance));
} else {
getValue(() -> method1("somestr", obj1instance, obj2instance, obj3instance));
}
}
private String method1(String s1, Obj1 s2, Obj2 s3, Obj3 s4){
//network call here to compute return value
return "computedmethod1";
}
private String method2(Obj5 s2, Obj6 s3){
//network call here to compute return value
return "computedmethod2";
}
public <T> T getValue(Supplier<T> supplier){
//this will call method1 or method2
//wrap the return value from supplier.get and return
return supplier.get();
}
更新基於安德魯的評論。
這使得很多道理,謝謝。我很難繞過供應商的概念。
C1.java
public C3 m1(Obj obj){
Supplier<String> mysupplier =() -> foo(arg1, arg2, arg3); //foo is an expensive call
return someFn(mysupplier);
}
如何在內部供應商的工作?當創建供應商時,是否保留對foo()的引用以及傳遞給foo的參數?
public C3 someFn(Supplier<String> supplier){
//this returns an instance of C3 that has a method lazyCall() which runs supplier.get()
}
C2.java
C3 c3 = c1.m1(obj);
如果當c3.lazyCall()被調用,它運行supplier.get()和Foo運行。這是供應商的有效用途嗎?
你的'mytest'沒有返回語句。它無法編譯。 –
你能否澄清你的意思是「任何問題」?由於此問題目前已編寫,因此它似乎是一個基於意見的問題(對於此站點而言,這是[off-topic](http://stackoverflow.com/tour))。 –
假設你要返回getValue,你使用的是泛型,但是所有的lambda只返回字符串。這隻會在T總是一個字符串時才起作用。 – Novaterata