zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Java8新特性-----方法引用和构造器引用

2023-03-14 22:35:09 时间

方法引用和构造器引用


方法引用的概念

若lambda体中的内容有方法已经实现了,我们可以使用方法引用

(我们可以理解为方法引用时lambda表达式的另外一种表现形式)


语法格式

对象::实例方法名

public class TestMain
{
    @Test
    void test()
    {
        PrintStream ps1=System.out;
        Consumer<String> con=(x)->ps1.println(x);

        PrintStream ps=System.out;
        Consumer<String> con1=ps::println;
        con1.accept("大忽悠");
    }
}
public class TestMain
{
    @Test
    void test()
    {
        People p=new People("大忽悠",18,3000);
        //lambda的写法
        Supplier<String> ss=()->p.getName();
        System.out.println(ss.get());
        //方法引用的写法
        Supplier<String> s=p::getName;
        System.out.println(s.get());
    }
}

注意:


类::静态方法名

//Comparator也是一个函数式接口
Comparator<Integer> c=(x,y)->Integer.compare(x,y);
//调用Integer的静态方法compare
Comparator<Integer> c1=Integer::compare;

类::实例方法名

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

        BiPredicate<String,String> bp=(x,y)->x.equals(y);
        BiPredicate<String,String> bp1=String::equals;

要求接口方法的参数必须比引用方法的参数多一个。而且第一个参数要是该引用方法的所在类型的或其父类,除接口方法的第一个参数以外, 其余参数的类型要求一样

class Test1
{
	public void a(int param1, int param2)
	{
		System.out.println("just a test");
	}
 
	public static void main(String[] args)
	{
 
		MyInter m = Test1::a;
	}
}
 
@FunctionalInterface
interface MyInter
{
	//该接口参数比上述的a方法参数数量多一个,除去第一个,其它类型一致(可兼容,如可以一个int,一个Integer)
	//且 interface 中 虚函数的一个参数一定是 引用方法所在类 类型
	void d(Test1 d, int param1, int param2);

注意

  1. lambda体中调用方法的参数列表和返回值类型,要与函数式接口中的抽象方法的函数列表和返回值类型保持一致
  2. 若Lambda参数列表中的第一个参数是实例方法的调用者,而第二个参数是实例方法的参数时,可以使用ClassName::method

构造器引用

需要调用的构造器的参数列表要与函数式接口中的参数列表保持一致

       Supplier<People> supplier=()->new People("大忽悠",18,5000);
        System.out.println(supplier.get());
       //构造器引用的方式:这里对应的是People类中的无参构造器
       Supplier<People> supplier1=People::new;
        System.out.println(supplier1.get());
   Function<Integer,People> function=(x)->new People(x);
        System.out.println(function.apply(18));
        //构造器引用
        Function<Integer,People> function1=People::new;
        System.out.println(function1.apply(20));
   //构造器引用
        BiFunction<String,Integer,People> function1=People::new;
        System.out.println(function1.apply("大忽悠",18));

people类里面的构造函数:

    public People(String name, Integer age, Integer money) {
        this.name = name;
        this.age = age;
        this.money = money;
    }

    public People(String name,Integer age)
    {
        this.name=name;
        this.age=age;
    }
    public People() {
    }
  public People(Integer age)
  {
      this.age=age;
  }

数组引用

      Function<Integer,String[]> function=(x)->new String[x];
        System.out.println(function.apply(10).length);
        //数组引用
        Function<Integer,String[]> function1=String[]::new;
        System.out.println(function1.apply(20).length);

详细可参考下面这篇文章

【Java8】 方法引用 讲解