我只有一个方法有这个
Java接口.
@H_403_2@// Java Interface
public interface AuditorAware {
Auditor getCurrentAuditor();
}
我使用Java 8 Lambda表达式来创建AuditorAware的内容如下.
@H_403_2@// Java 8 Lambda to create instance of AuditorAware public AuditorAware currentAuditor() { return () -> AuditorContextHolder.getAuditor(); }我试图在Groovy中编写Java实现.
我看到有很多方法可以在groovy中实现接口,如本Groovy ways to implement interfaces文档所示.
我已经在Java代码上实现了groovy等效,通过使用带有map的实现接口,如上面提到的文档中所示.
@H_403_2@// Groovy Equivalent by "implement interfaces with a map" method AuditorAware currentAuditor() { [getCurrentAuditor: AuditorContextHolder.auditor] as AuditorAware }但是,如文档示例所示,使用闭包方法实现接口似乎更简洁.但是,当我尝试按如下方式实现时,IntelliJ显示错误代码模糊代码块.
@H_403_2@// Groovy Equivalent by "implement interfaces with a closure" method ??? AuditorAware currentAuditor() { {AuditorContextHolder.auditor} as AuditorAware }如何通过使用“使用闭包实现接口”方法将Java 8 lambda实现更改为groovy等效?
解决方法
正如
Dylan Bijnagte所述,以下代码有效.
@H_403_2@// Groovy Equivalent by "implement interfaces with a closure" method
AuditorAware currentAuditor() {
{ -> AuditorContextHolder.auditor} as AuditorAware
}
章节参数Documentation on Groovy Closure的说明解释了这一点.