以前调用:对象.方法名、类名.方法名
jdk1.8提供了另外一种调用方式 ::
用来直接访问类 或者实例已经存在的方法或构造方法
通过方法引用,可以将方法的引用赋值给一个变量
左边是容器(可以是类名,实例名)
中间是”::"
右边是方法名
- package com.learning.javalearning.lambda.chapter4;
-
- import java.util.function.BiFunction;
- import java.util.function.Function;
-
- public class Adduce {
- public static void main(String[] args) {
-
-
- //使用双冒号:: 来构造静态函数的引用
- // Integer.parseInt("wew);
- Function
fun = Integer::parseInt; - Integer value = fun.apply("1024");
- System.out.println(value);
-
- //使用双冒号::来构造非静态函数引用
- String content ="非静态函数引用";
- Function
func = content::substring; - String result = func.apply( 1);
- System.out.println(result);
-
- // 2个入参
- BiFunction
biFunction = User::new; - User user1 = biFunction.apply("张无忌",1);
- System.out.println(user1);
-
- // 1个入参
- Function
function = User::new; - User user2 = function.apply("赵敏");
- System.out.println(user2);
-
- sayHello(String::toUpperCase,"abvdefg");
-
- }
-
- private static void sayHello(Function
func,String param) { - String result = func.apply(param);
- System.out.println(result);
- }
- }
-
- class User {
- private String name;
- private int age;
-
- public User() {
- }
-
- public User(String name, int age) {
- this.name = name;
- this.age = age;
- }
-
- public User(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return "User{" +
- "name='" + name + '\'' +
- ", age=" + age +
- '}';
- }
- }
className::methodName
- //使用双冒号:: 来构造静态函数的引用
- // Integer.parseInt("wew);
- Function
fun = Integer::parseInt; - Integer value = fun.apply("1024");
- System.out.println(value);
Instance::methodName
- //使用双冒号::来构造非静态函数引用
- String content ="非静态函数引用";
- Function
func = content::substring; - String result = func.apply( 1);
- System.out.println(result);
类名::new
- // 1个入参
- Function
function = User::new; - User user2 = function.apply("赵敏");
- System.out.println(user2);
- // 2个入参
- BiFunction
biFunction = User::new; - User user1 = biFunction.apply("张无忌",1);
- System.out.println(user1);
