java方法引用的使用详解

使用情境

当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用。

方法引用的本质

本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例。所以
方法引用,也是函数式接口的实例。

使用格式:

类(或对象) :: 方法名

具体分为如下的三种情况
情况1 对象 :: 非静态方法
情况2 类 :: 静态方法
情况3 类 :: 非静态方法

方法引用使用的要求:

要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的
形参列表和返回值类型相同!(针对于情况1和情况2)

理解的关键

如果你要使用lambda函数,而且有现成的方法可以实现lambda表达式要做的功能,那么就可以使用方法引用了。
比如下面test3里要实现比较两个数大小的功能,comparator是一个函数式接口,我们可以选择使用lambda表达式;而Integer的compare方法已经实现了一样的功能(传给它两个数,它会比较这两个数的大小),这时候就可以选择方法引用,直接用Integer::compare代替整个lambda表达式。

使用举例

情况一:对象 :: 实例方法

   //Consumer中的void accept(T t)
   //PrintStream中的void println(T t)
   @Test
   public void test1() {
      Consumer<String> con1 = str -> System.out.println(str);
      con1.accept("北京");

      System.out.println("*******************");
      PrintStream ps = System.out;
      Consumer<String> con2 = ps::println;
      con2.accept("beijing");
   }
   
   //Supplier中的T get()
   //Employee中的String getName()
   @Test
   public void test2() {
      Employee emp = new Employee(1001,"Tom",23,5600);

      Supplier<String> sup1 = () -> emp.getName();
      System.out.println(sup1.get());

      System.out.println("*******************");
      Supplier<String> sup2 = emp::getName;
      System.out.println(sup2.get());

   }

情况二:类 :: 静态方法

   //Comparator中的int compare(T t1,T t2)
   //Integer中的int compare(T t1,T t2)
   @Test
   public void test3() {
      Comparator<Integer> com1 = (t1,t2) -> Integer.compare(t1,t2);
      System.out.println(com1.compare(12,21));

      System.out.println("*******************");

      Comparator<Integer> com2 = Integer::compare;
      System.out.println(com2.compare(12,3));
   //Integer的compare方法已经实现了一样的功能(传给它两个数,它会比较这两个数的大小),
   //这时候就可以选择方法引用,直接用Integer::compare代替整个lambda表达式
   }
   
   //Function中的R apply(T t)
   //Math中的Long round(Double d)
   @Test
   public void test4() {
      Function<Double,Long> func = new Function<Double, Long>() {
         @Override
         public Long apply(Double d) {
            return Math.round(d);
         }
      };

      System.out.println("*******************");

      Function<Double,Long> func1 = d -> Math.round(d);
      System.out.println(func1.apply(12.3));

      System.out.println("*******************");

      Function<Double,Long> func2 = Math::round;
      System.out.println(func2.apply(12.6));
   }

情况三:类 :: 实例方法

   // Comparator中的int comapre(T t1,T t2)
   // String中的int t1.compareTo(t2)
   @Test
   public void test5() {
      Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);
      System.out.println(com1.compare("abc","abd"));

      System.out.println("*******************");

      Comparator<String> com2 = String :: compareTo;
      System.out.println(com2.compare("abd","abm"));
   }

   //BiPredicate中的boolean test(T t1, T t2);
   //String中的boolean t1.equals(t2)
   @Test
   public void test6() {
      BiPredicate<String,String> pre1 = (s1,s2) -> s1.equals(s2);
      System.out.println(pre1.test("abc","abc"));

      System.out.println("*******************");
      BiPredicate<String,String> pre2 = String :: equals;
      System.out.println(pre2.test("abc","abd"));
   }
  
   // Function中的R apply(T t)
   // Employee中的String getName();
   @Test
   public void test7() {
      Employee employee = new Employee(1001, "Jerry", 23, 6000);


      Function<Employee,String> func1 = e -> e.getName();
      System.out.println(func1.apply(employee));

      System.out.println("*******************");


      Function<Employee,String> func2 = Employee::getName;
      System.out.println(func2.apply(employee));


   }

这里用到了java内置的函数式接口,不懂的话可以看这个链接:
https://blog.csdn.net/weixin_48262684/article/details/124481512
lambda表达式使用的介绍见这个链接:
https://blog.csdn.net/weixin_48262684/article/details/124478950

如果大家看的有点乱,可以放IDE里测试,自行创建测试类将上面代码复制进去即可。
这里用到了Employee类,是自定义的类。

能看懂的看到这就可以了

附Employee代码

public class Employee {

	private int id;
	private String name;
	private int age;
	private double salary;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public Employee() {

	}

	public Employee(int id) {

		this.id = id;
	}

	public Employee(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public Employee(int id, String name, int age, double salary) {

		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	@Override
	public String toString() {
		return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}';
	}

	@Override
	public boolean equals(Object o) {
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;

		Employee employee = (Employee) o;

		if (id != employee.id)
			return false;
		if (age != employee.age)
			return false;
		if (Double.compare(employee.salary, salary) != 0)
			return false;
		return name != null ? name.equals(employee.name) : employee.name == null;
	}

	@Override
	public int hashCode() {
		int result;
		long temp;
		result = id;
		result = 31 * result + (name != null ? name.hashCode() : 0);
		result = 31 * result + age;
		temp = Double.doubleToLongBits(salary);
		result = 31 * result + (int) (temp ^ (temp >>> 32));
		return result;
	}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,参数传递有两种方式:值传递和引用传递。值传递是指将实际参数的值复制一份给形式参数,而引用传递是指将实际参数的引用(地址)复制一份给形式参数。 Java中的基本数据类型(如int、float等)都是采用值传递的方式进行参数传递。这意味着在方法内部修改形式参数的值不会影响到实际参数的值。 而对于对象类型,Java采用的是引用传递。当将一个对象作为参数传递给方法时,实际上传递的是对象的引用(地址),而不是对象本身。这意味着在方法内部修改对象的属性值会影响到实际对象的属性值。 需要注意的是,虽然对象的引用被传递给了方法,但是如果在方法内部将引用指向了一个新的对象,那么这个改变不会影响到原始对象。 下面是一个示例代码来说明Java中的引用传递: ```java public class Main { public static void main(String[] args) { Person person = new Person("Alice"); System.out.println("Before changeName method: " + person.getName()); changeName(person); System.out.println("After changeName method: " + person.getName()); } public static void changeName(Person p) { p.setName("Bob"); } } class Person { private String name; public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` 输出结果为: ``` Before changeName method: Alice After changeName method: Bob ``` 在上述代码中,通过引用传递将`person`对象传递给`changeName`方法方法内部修改了对象的属性值,导致在方法外部也能看到修改后的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值