在js中方法是作为对象是可以传递的,当然c语言中方法也可以使用指针来传递,java中的话可以使用接口来传递方法,但是毕竟不像js这样方便。Java 8新特性里面提供了新的方式来传递方法对象。
使用场景
我们用Lambda表达式来实现匿名方法。但有些情况下,我们用Lambda表达式仅仅是调用一些已经存在的方法,除了调用动作外,没有其他任何多余的动作,在这种情况下,我们倾向于通过方法名来调用它,而Lambda表达式可以帮助我们实现这一要求,它使得Lambda在调用那些已经拥有方法名的方法的代码更简洁、更容易理解。方法引用可以理解为Lambda表达式的另外一种表现形式。
方法引用的分类
静态方法引用 | 类名::staticMethod | (args) -> 类名.staticMethod(args) |
实例方法引用 | inst::instMethod | (args) -> inst.instMethod(args) |
对象方法引用 | 类名::instMethod | (inst,args) -> 类名.instMethod(args) |
构建方法引用 | 类名::new | (args) -> new 类名(args) |
举例
Consumer<String> test = (str) -> System.out.println(str);
test .accept("Hello");
TestObj testObj = new TestObj("Moti",10,"男");
Supplier<String> test= testObj::getName;
System.out.println(test.get());