lambda - 方法引用
方法引用是一种更为简洁的代码构造,它可以让你直接引用已有Java类的方法或者构造器,你可以通过使用::关键字来引用一个方法。
方法引用可以分为以下三种:
- 静态方法引用
- 实例方法引用
- 构造函数引用
下面是一些示例代码:
// 静态方法引用
Function<String, Integer> function = Integer::parseInt;
Integer result = function.apply("123");
System.out.println(result); // 输出:123
// 实例方法引用
String test = "Hello, World!";
Supplier<Integer> supplier = test::length;
int length = supplier.get();
System.out.println(length); // 输出:13
// 构造函数引用
Supplier<Test> supplier = Test::new;
Test test = supplier.get();
日常应用
package com.sea.bean;
@FunctionalInterface
interface ClickListenner<T> {
void onclick(T a);
}
class Receiver {
public void doclick(String msg) {
System.out.println(msg);
}
}
class Provider {
private ClickListenner<String> listenner;
public Provider(ClickListenner<String> listenner) {
this.listenner = listenner;
}
public void sendMessage() {
listenner.onclick("click...");
}
}
public class TestA {
public static void main(String[] args) {
{
//原始写法
Receiver receiver = new Receiver();
Provider provider = new Provider(new ClickListenner<String>() {
@Override
public void onclick(String msg) {
receiver.doclick(msg);
}
});
provider.sendMessage();
}
{
// Lambda下的简写
Receiver receiver = new Receiver();
Provider provider = new Provider((msg) -> {
receiver.doclick(msg);
});
provider.sendMessage();
}
{
// Lambda下的极简写法
Receiver receiver = new Receiver();
Provider provider = new Provider(receiver::doclick);
provider.sendMessage();
}
}
}
疯狂的妞妞 :每一天,做什么都好,不要什么都不做!