3年前 (2021-06-28)  Java系列 |   抢沙发  268 
文章评分 0 次,平均分 0.0
[收起] 文章目录

方法引用是Java8中用于调用方法的lambda表达式的简写表示法。例如:

如果lambda表达式如下:

str -> System.out.println(str)

然后可以用如下方法引用替换它:

System.out::println

在方法引用中使用 :: 运算符将类或对象与方法名分开(我们将通过示例来了解这一点)。

四种方法引用

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

2.对类的静态方法的方法引用–class::staticMethod

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

4.对构造函数的方法引用–Class::new

对象实例方法的方法引用

@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

对类的静态方法的方法引用

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

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

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

对构造函数的方法引用

@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!
 

除特别注明外,本站所有文章均为老K的Java博客原创,转载请注明出处来自https://javakk.com/2068.html

关于

发表评论

表情 格式

暂无评论

登录

忘记密码 ?

切换登录

注册