java groovy 表达式,Java Lambda表达式与Groovy闭包的逻辑类似吗?

I learn about java 8 new feature Lambda expressions. So this is my "HelloWorld" class using Lambda expression

public class LambdaHelloWorld {

interface HelloWorld {

String sayHello(String name);

}

public static void main(String[] args) {

HelloWorld helloWorld = (String name) -> { return "Hello " + name; };

System.out.println(helloWorld.sayHello("John Doe"));

}

}

This style is so similar to Groovy closure. This is groovy "HelloWorld"

def sayHello(name) {

println("Hello $name!")

}

def clos = {name -> sayHello(name)} clos.call('John Doe')

I think these two codes are less difference between each others.Is Java Lambda expression is similar logic or style of Groovy closure?

解决方案

Implementing a so-called functional interface in Java 8 (with lambdas) or in Groovy (with closures) looks quite the same, but underlying mechanisms are pretty different. Let's take the java.util.function.Consumer functional interface as an example. We use it to call the new Java 8 forEach() method on a hypothetic java.util.List instance called myList.

In Java it looks like this:

myList.forEach ((s) -> System.out.println(s));

The same in Groovy:

myList.forEach { s -> println s }

Both compilers generate new Classes from the lambda / closure code. The class generated by Java 8 implements the target interface (Consumer in this case), not derived from anything, similar to an embedded anonymous class like this:

myList.forEach(new Consumer() {

@Override

public void accept (Object s) {

System.out.println(s);

}

});

In contrast, what Groovy generates looks a little bit like the following:

myList.forEach (new Closure(this) {

void doCall(Object s) {

println s

}

}

This creates an anonymous class derived from groovy.lang.Closure that does not implement any specific interface. Nevertheless, it can be used as parameter here. This is possible because Groovy generates a dynamic proxy object at runtime, implementing the ´Consumer´ interface and forwarding any calls to the generated Closure instance.

As a consequence, you can replace Java 8 lambdas by Groovy closures, but not the other way round. When you want to use a Groovy API in Java 8 code, you cannot call a method expecting a Closure with a lambda expression. Closure isn't a functional interface but an abstract class, and that can simply not be implemented by a lambda expression.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值