Skip to content

Latest commit

 

History

History
134 lines (109 loc) · 3.01 KB

60.md

File metadata and controls

134 lines (109 loc) · 3.01 KB

Java 8 中的方法引用

原文: https://beginnersbook.com/2017/10/method-references-in-java-8/

在上一个教程中,我们在 Java 8 中学习了 lambda 表达式。这里我们将讨论 java 8 的另一个新特性,方法引用。方法引用是用于调用方法的 lambda 表达式的简写表示法。例如: 如果你的 lambda 表达式是这样的:

str -> System.out.println(str)

然后你可以用这样的方法引用替换它:

System.out::println

::运算符用于方法引用,以将类或对象与方法名称分开(我们将在示例的帮助下学习)。

四种方法引用

  1. 对象的实例方法的方法引用 - object::instanceMethod
  2. 类的静态方法的方法引用 - class::staticMethod
  3. 特定类的任意对象的实例方法的方法引用 - Class::instanceMethod
  4. 构造函数的方法引用 - Class::new

1.方法引用:对象的实例方法

@FunctionalInterface 
interface MyInterface{  
    void display();  
}  
public class Example {  
    public void myMethod(){  
	System.out.println("Instance Method");  
    }  
    public static void main(String[] args) {  
	Example obj = new Example();   
	// Method reference using the object of the class
	MyInterface ref = obj::myMethod;  
	// Calling the method of functional interface  
	ref.display();  
    }  
}

输出:

Instance Method

2.方法引用:类的静态方法

import java.util.function.BiFunction;  
class Multiplication{  
   public static int multiply(int a, int b){  
	return a*b;  
   }  
}  
public class Example {  
   public static void main(String[] args) {  
	BiFunction<Integer, Integer, Integer> product = Multiplication::multiply;  
	int pr = product.apply(11, 5);  
	System.out.println("Product of given number is: "+pr);  
   }  
}

输出:

Product of given number is: 55

3.方法引用:特定类型的任意对象的实例方法

import java.util.Arrays;
public class Example {  

   public static void main(String[] args) {  
	String[] stringArray = { "Steve", "Rick", "Aditya", "Negan", "Lucy", "Sansa", "Jon"};
	/* Method reference to an instance method of an arbitrary 
	 * object of a particular type
	 */
	Arrays.sort(stringArray, String::compareToIgnoreCase);
	for(String str: stringArray){
		System.out.println(str);
	}
   }  
}

输出:

Aditya
Jon
Lucy
Negan
Rick
Sansa
Steve

4.构造函数的方法引用

@FunctionalInterface 
interface MyInterface{  
    Hello display(String say);  
}  
class Hello{  
    public Hello(String say){  
        System.out.print(say);  
    }  
}  
public class Example {  
    public static void main(String[] args) { 
    	//Method reference to a constructor
        MyInterface ref = Hello::new;  
        ref.display("Hello World!");  
    }  
}

输出:

Hello World!