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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章