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));
		
	}
}

 

全部评论

相关推荐

点赞 评论 收藏
分享
05-23 20:31
已编辑
武汉大学 Java
内向的柠檬精在研究求职打法:注意把武大标粗标大 本地你俩不是乱杀
点赞 评论 收藏
分享
06-18 16:45
门头沟学院 Java
玩脱了,吊着两家结果两家都不要鼠鼠了,我真想给自己两巴掌。
凉风落木楚山秋:当作是你把这两家公司从地球开除了就行了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务