java8 Lambda ::的几种目标方法引用方式

首先定义一个调用方法、和目标方法

//调用方法
public void doWithTargetMethod(BiConsumer<String, String> biConsumer,String key,String value) {
		biConsumer.accept(key,value);
	}
//目标方法1
public void targetMethod(String msg,String value) {
		System.out.println(msg+":"+value);
	}
//目标方法2
public void targetMethod2( String a){
		System.out.println(a+" param :" +this.key);
	}
//目标方法3
public static void  targetMethod3(String msg,String value) {
		System.out.println(msg+":"+value);
	}

传统调用方式

doWithTargetMethod(new BiConsumer<String, String>() {

			@Override
			public void accept(String t, String u) {
				targetMethod(t,u);
			}
		}, "hello", "eshin");

一般Lambda 表达式调用

//调用时如下
doWithTargetMethod((k,v)->{targetMethod(k,v);}, "hello","eshin");

使用‘::’进行方法引用 通过实例对非静态方法的引用
//需要通过实例调用
doWithTargetMethod(new TestMethod()::targetMethod, "hello","eshin1");

通过类对静态方法的引用

doWithTargetMethod(TestMethod::targetMethod3,"hello","eshin3");

通过类对非静态方法的引用

//第一个参数需与类名一致
BiConsumer<TestMethod, String> consumer2 = TestMethod::targetMethod2;
TestMethod tm = new TestMethod();
//调用accept方法时,传入对应类的实例,作为目标方法的this
consumer2.accept(tm,"eshin");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值