JDK8系列之Method References教程和示例

旧城等待, 2021-09-09 00:36 344阅读 0赞

JDK8系列之方法引用教程和示例

在上一章的学习中,我们学习了JDK8的lambada表达式,接着,本章节继续学习jdk8的方法引用

1、什么是jdk8方法引用

方法引用,英文Method References,jdk8中的方法引用通过方法的名字来指向一个方法,语法是使用一对冒号 ::,方法引用可以使语言的构造更紧凑简洁,减少冗余代码

2、方法引用的分类

方法引用的使用有如下几种:

  • 类的静态方法引用,类名::静态方法名
    语法:ClassName :: staticMethodName
  • 特定对象的实例方法引用,对象::实例方法名
    语法:object :: instanceMethodName
  • 类的任意对象的实例方法引用,类名::实例方法名
    语法:ClassName :: instanceMethodName
  • 构造器引用,类名::new(构造方法的引用)
    语法:ClassName :: new

3、类的静态方法引用

  1. import java.util.function.BiFunction;
  2. public class MethodReferenceExample {
  3. public MethodReferenceExample() {
  4. }
  5. public static void main(String[] args) {
  6. // example 1:引用类的静态方法
  7. BiFunction<Integer , Integer , Integer> add = MethodReferenceExample::add;
  8. int pr1 = add.apply(5 , 20);
  9. System.out.println(String.format("两个数相加的和:%s" , pr1));
  10. }
  11. public static int add(int a , int b) {
  12. return a + b;
  13. }
  14. }

4、类的任意对象的实例方法引用

  1. import java.util.Arrays;
  2. public class MethodReferenceExample {
  3. public MethodReferenceExample() {
  4. }
  5. public static void main(String[] args) {
  6. // example 2:引用类的实例方法
  7. String[] strs = { "Apple", "Banana" , "Apricot","Cumquat", "Grape", "Lemon","Loquat","Mango"};
  8. Arrays.sort(strs , String::compareToIgnoreCase);
  9. Arrays.asList(strs).forEach(str -> { System.out.println(String.format("水果名称:%s", str));});
  10. }
  11. }

5、特定对象的实例方法引用

  1. public class MethodReferenceExample {
  2. public MethodReferenceExample() {
  3. }
  4. public static void main(String[] args) {
  5. // example 3:引用对象的实例方法
  6. MethodReferenceExample example = new MethodReferenceExample();
  7. MyFunctionalInterface functionalInterface = example::echo;
  8. functionalInterface.display();
  9. }
  10. public void echo() {
  11. System.out.println("hello world");
  12. }
  13. }
  14. @FunctionalInterface
  15. interface MyFunctionalInterface{
  16. void display();
  17. }

6、对构造函数的方法引用

  1. public class MethodReferenceExample {
  2. public MethodReferenceExample() {
  3. }
  4. public MethodReferenceExample(String msg) {
  5. System.out.println(String.format("参数打印:%s" , msg));
  6. }
  7. public static void main(String[] args) {
  8. // example 4:构造方法的引用
  9. MyInterface myInterface = MethodReferenceExample::new;
  10. myInterface.display("Method reference to a constructor");
  11. }
  12. }
  13. @FunctionalInterface
  14. interface MyInterface{
  15. void display(String msg);
  16. }

附录:参考资料

  • https://www.runoob.com/java/java8-new-features.html

发表评论

表情:
评论列表 (有 0 条评论,344人围观)

还没有评论,来说两句吧...

相关阅读

    相关 java8 [method reference]

    原文:[method reference][] lambda表达式通常用匿名方法。而有时候,lambda表达式做的仅仅是调用一个已经存在的方法,可以通过函数名调用该函数,即m