[英]Groovy equivalent for Java 8 Lambda Expression
我只有一個方法有這個Java接口。
// Java Interface
public interface AuditorAware {
Auditor getCurrentAuditor();
}
我使用Java 8 Lambda表達式來創建AuditorAware
的內容如下。
// Java 8 Lambda to create instance of AuditorAware
public AuditorAware currentAuditor() {
return () -> AuditorContextHolder.getAuditor();
}
我試圖在Groovy中編寫Java實現。
我看到有很多方法可以在groovy中實現接口,如Groovy實現接口文檔的方法所示。
我已經在Java代碼上實現了groovy等效,通過使用帶有map的實現接口,如上面提到的文檔中所示。
// Groovy Equivalent by "implement interfaces with a map" method
AuditorAware currentAuditor() {
[getCurrentAuditor: AuditorContextHolder.auditor] as AuditorAware
}
但是,如文檔示例所示,使用閉包方法實現接口似乎更簡潔。 但是,當我嘗試按如下方式實現時, IntelliJ
顯示錯誤代碼模糊代碼塊 。
// Groovy Equivalent by "implement interfaces with a closure" method ???
AuditorAware currentAuditor() {
{AuditorContextHolder.auditor} as AuditorAware
}
如何通過使用“使用閉包實現接口”方法將Java 8 lambda實現更改為groovy等效?
由Dylan Bijnagte評論,以下代碼有效。
// Groovy Equivalent by "implement interfaces with a closure" method
AuditorAware currentAuditor() {
{ -> AuditorContextHolder.auditor} as AuditorAware
}
關於Groovy Closure的文檔的 Paramter注釋說明了這一點。
您可以使用.&
運算符來獲取方法參考:
class Auditor {
String name
}
interface AuditorAware {
Auditor getCurrentAuditor()
}
class AuditorContextHolder {
static getAuditor() { new Auditor(name: "joe") }
}
AuditorAware currentAuditor() {
AuditorContextHolder.&getAuditor
}
assert currentAuditor().currentAuditor.name == "joe"
在Java 8中,您可以使用::
for方法引用:
AuditorAware currentAuditor() {
return AuditorContextHolder::getAuditor;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.