java 方法引用

lambda和方法引用都遵循SAM(single abstract method)规则,即一个抽象类中只有一个抽象方法

利用方法引用的概念可以为一个方法定义多个名字,但是要求必须是函数式接口(SAM)。

package test;

// 方法引用
@FunctionalInterface	// 函数式接口
interface IFunc1<P,R>{
	public R change(P p);
}

@FunctionalInterface	// 函数式接口
interface IFunc2{
	public String toUpper();
}
@FunctionalInterface	// 函数式接口
interface IFunc3<T>{
	public int strcmp(T t1, T t2);
}

class Person{
	private String name;
	private int age;
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public String toString() {
		return "name: " + this.name + ", age: " + this.age;
	}
}
@FunctionalInterface	// 函数式接口
interface IFunc4<P>{
	public P create(String name, int age) ;
}

public class Main{
	
	public static void main(String args[]) {
		IFunc1<Integer, String> fun = String::valueOf;	// 引用静态方法
		String str = fun.change(100);
		System.out.println(str.length());
		System.out.println(String.valueOf(1.23));
		
		String str2 = "www.baidu.com";
		IFunc2 fun2 = str2::toUpperCase;	// 引用普通方法
		System.out.println(fun2.toUpper());
		
		IFunc3<String> fun3 = String::compareTo;	// 引用特定类的方法,绕过实例化对象
		System.out.println(fun3.strcmp("123", "456"));
		
		
		IFunc4<Person> fun4 = Person::new;	// 引用构造方法
		System.out.println(fun4.create("abc", 20));
		
	}
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值