Java8方法引用及构造方法引用原理实例解析

作者:Chsoul'S Blog 时间:2022-07-24 08:21:22 

如果不熟悉Java8新特性的小伙伴,初次看到函数式接口写出的代码可能会是一种懵逼的状态,我是谁,我在哪,我可能学了假的Java,(・∀・(・∀・(・∀・*),但是语言都是在进步的,就好比面向对象的语言Java也可以写出优雅的函数式调用,学习的过程并不复杂,当你学会了Java8中函数式编程的新特性,你一定会对他爱不释手的。下面介绍一下基于Lambda表达式简写的两种引用。避免再次看到这种代码时的尴尬😅。

方法引用

方法引用,一般包含下面三种写法,传统的写法我们可能都是通过对象.去调用实例方法或使用类.调用静态方法,但是学完方法引用后,就可以可以使用这三种方式去调用方法,但是要符合一定的规则。

对象::实例方法


/**
* 对象调用实例方法
*/
public static void objMethod(){
 List<Integer> list = new ArrayList<> ();
 list.add(1);
 list.add(2);
 list.add(3);

list.forEach((i)->{
   PrintStream out = System.out;
   Consumer<Integer> consumer = out::println;
   consumer.accept(i);
 });
 list.forEach(System.out::println);
}

最常用的System.out.println

类::实例方法


/**
* 判断两个字符串是否相同
*
* @param str1
* @param str2
* @return
*/
public static boolean isEqual(String str1, String str2) {
 BiPredicate<String,String> b = (s1,s2)->s1.equals(str2); ①
 BiPredicate<String, String> bp = String::equals;
 return bp.test(str1, str2);
}

类::静态方法


/**
* 比较大小
* @param x
* @param y
* @return
*/
public static boolean compareValue(int x, int y){
 Comparator<Integer> compare = Integer::compare; ②
 return compare.compare(x, y) > 0;
}

其实不管是哪一种调用方式都是有规律可循的,这里总结一下在使用Lambda表达式的过程中符合什么样的规则才可以使用方法引用的模式去写。

Lambda体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数列表和返回值类型保持一致 Integer::compare ②

Lambda参数列表中的第一参数是实例方法的调用者,而第二个参数是实例方法的参数时 可以使用ClassName::method ①
构造方法引用#

简称花式new对象,一个简单的new对象也要写的高端、大气、上档次😄,既可以掌握新知识,又可以ZB,赶紧学习吧。

ClassName::new

资源类:


public class Apple {
 private String color;
 private double weight;

public Apple(){

}
 public Apple(String color) {
   this.color = color;
 }
 public Apple(double weight) {
   this.weight = weight;
 }
 public Apple(String color, double weight) {
   this.color = color;
   this.weight = weight;
 }
 public String getColor() {
   return color;
 }
 public void setColor(String color) {
   this.color = color;
 }
 public double getWeight() {
   return weight;
 }
 public void setWeight(double weight) {
   this.weight = weight;
 }
 @Override
 public String toString() {
   return "Apple{" +
       "color='" + color + '\'' +
       ", weight=" + weight +
       '}';
 }
}

测试代码:


public static void main(String[] args) {
 //无参构造
 //Supplier<Apple> supplier = () -> new Apple(); Lambda表达式写法
 Supplier<Apple> supplier = Apple::new;
 Apple apple = supplier.get();
 System.out.println("NoArgsConstructor: "+apple);

//有参构造
 //Function<Double,Apple> function = (x) -> new Apple(x);  Lambda表达式写法
 // 构造引用
 Function<Double,Apple> function = Apple::new;
 Apple apply = function.apply(1.0);
 System.out.println("OneArgsConstructor: "+apply);

BiFunction<String,Double,Apple> bf = Apple::new;
 Apple bi = bf.apply("Red", 2.0);
 System.out.println("TwoArgsConstructor: "+bi);
}

输出结果:

NoArgsConstructor: Apple{color='null', weight=0.0}
OneArgsConstructor: Apple{color='null', weight=1.0}
TwoArgsConstructor: Apple{color='Red', weight=2.0}

当构造方法无参时使用Supplier,有一个参数时使用Function,两个参数时使用BiFunction。这里很容易得出一个规律,当使用构造方法引用时,函数式接口的参数列表需要和构造方法的参数列表保持一致。

我们也可以用这些函数式接口改写传统的创建数组的方式,初始化一个指定长度的数组,比如

Function<Integer,String[]> fun = String[]::new;
String[] strArr = fun.apply(10);

也可以这样写:


public static <T> T[] initArray(int num, Function<Integer,T[]> function){
 return function.apply(num);
}

调用:

Copy
Apple[] strings = initArray(10, x -> new Apple[x]);
System.out.println(strings.length);

疑惑

根据传入的参数返回指定的对象数组引用,不过这样还不如直接创建。不知道读者有没有考虑这里为什么不可以用一个泛型来new,那样就可以创建一个通用数组引用,但是Java中的泛型是伪泛型,在编译器就会进行泛型擦除,所以不能通过new关键字来创建一个泛型对象,具体内容可以在查阅其他资料了解泛型以及泛型擦除的原理,这里不做深究。

来源:https://www.cnblogs.com/chsoul/p/13622489.html

标签:Java,方法,引用,构造
0
投稿

猜你喜欢

  • mybatis中<if>标签bool值类型为false判断方法

    2023-11-20 11:28:33
  • java基础二叉搜索树图文详解

    2023-06-01 05:43:19
  • SpringBoot项目从搭建到发布一条龙

    2023-11-21 09:28:44
  • 一篇文章带你入门Java基本概念

    2023-11-26 01:17:08
  • eclipse实现ElGamal数字签名

    2023-11-26 07:52:47
  • java打印指定年月的日历

    2023-11-11 19:21:19
  • 详解如何实现SpringBoot的底层注解

    2023-11-23 06:21:04
  • Java内存模型(JMM)及happens-before原理

    2023-11-25 00:41:05
  • 详解Android的.aar文件生成方法以及使用技巧

    2023-08-06 06:43:20
  • Java_异常类(错误和异常,两者的区别介绍)

    2023-09-19 08:53:27
  • iOS中的导航栏UINavigationBar与工具栏UIToolBar要点解析

    2023-07-08 16:52:22
  • Spring boot整合log4j2过程解析

    2023-11-29 10:47:53
  • C# DataGridView添加新行的2个方法

    2023-06-23 05:42:19
  • Android集成腾讯X5实现文档浏览功能

    2023-10-03 23:44:06
  • JavaWeb项目部署到服务器详细步骤详解

    2023-11-29 11:15:20
  • Java中接收键盘输入的三种方法

    2023-11-13 16:11:29
  • springBoot之如何获取接口请求数据和返回数据实现日志

    2023-11-23 10:43:58
  • 安卓GreenDao框架一些进阶用法整理

    2023-06-17 03:27:21
  • Java基于享元模式实现五子棋游戏功能实例详解

    2023-07-23 16:20:18
  • Spring Security前后分离校验token的实现方法

    2023-06-26 17:00:30
  • asp之家 软件编程 m.aspxhome.com