java的非静态方法,Java 8中使用非静态方法的lambda

这篇博客探讨了Java 8中Lambda表达式的使用,特别是关于方法引用的一个有趣现象。即使非静态方法如`Integer::compareTo`也能被赋值给Comparator接口,尽管它只需要一个参数。作者指出,这是因为编译器能够根据方法签名识别出所引用的方法类型,从而在调用时正确处理。这种行为被称为实例捕获。Lambda表达式并非面向对象世界的概念,它们允许更简洁的代码表示和方法调用方式。
摘要由CSDN通过智能技术生成

I am trying to learnd lambdas in new Java 8. There is one interesting thing. If method has the same signature as functional interface, it can be assigned to it using lambdas API. For instance.

Comparator myComp = Integer::compare;

This method(Integer.compare) is static, takes two values, everything is perfect. the signature the same as in interface method compare. BUT this can be made with non-static methods, for example

Comparator myComp = Integer::compareTo.

This method is non-static (instance level) and furthermore, it takes only one value. As I have understood, there is no non-static methods in Java, every method is static but if it is not marked as static it takes this as the first parameter. As following

compareTo(this,Integer value).

It would be reasonable to assume that result will be undefined because of comparing object and integer. BUT THIS WORKS.

Comparator comparator = Integer::compareTo;

Comparator comparator2 = Integer::compare;

System.out.println(comparator.compare(1,2));

System.out.println(comparator2.compare(1,2));

This works equally.

I have debugged call method stack. While calling method compare of comparator object without creating instance, this. Value is already initialized by the first parameter and of course this is valid reference to the object.

SO the question is How does this work? While calling method compiler checks, if the class has only one field which has the same type as first param in method, if class has compiler implictly creates new instance of the class with initialized field or how does it work?

解决方案

This is because lambdas are not from Object Oriented world.

When you assign some method to Comparator it's task is to perform the comparision.

Comparator methodOne = Integer::compare;

Comparator methodTwo = Integer::compareTo;

This methodOne.compare(1,2); will be translated to Integer.compare(1,2) it is called non-instance-capturing and refer to static method

This methodTwo.compare(1,2); will be translated to 1.compareTo(2) is is called instance-capturing and refers to instance methods.

Compiler "knows" what type of method you have referenced so it can process without error.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值