方法引用
需要合适的函数接口来接收。函数接口中的抽象函数参数列表与返回值,,要与方法或静态方法的 参数列表和返回值相对应。
- 静态方法的引用、
Lambda参数是示例方法的参数,则可以使用
package cn.unuuc.java.methed;
@FunctionalInterface
interface Converter<F,T>{
T convert(F from);
}
public class Test {
public static void main(String[] args) {
// 使用Lambda
Converter<String,Integer> converter1 = (from -> Integer.valueOf(from));
// 静态方法引用,valueOf为静态方法
Converter<String,Integer> converter2 = Integer::valueOf;
}
}
上面的示例中演示了静态方法的引用,通过 ::
的形式,将静态方法替代了Lambda中的方法体部分。
- 对象方法的引用
对象方法的引用,一定是存在对象的情况下,对对象进行引用,没有对象则无法引用。
package cn.unuuc.java.methed;
import cn.unuuc.java.MyFunctionalInterface;
import java.util.function.Function;
class Demo{
public String hello(){
return "hello";
}
public static String world(String s){
return "world";
}
}
public class Test {
public static void main(String[] args) {
Demo demo = new Demo();
// MyFunctionalInterface是自定义的函数接口
MyFunctionalInterface hello = demo::hello;
// 静态方法需要传参,需要使用函数接口类型来接受
Function<String, String> world = Demo::world;
}
}
- 第三种情况
函数接口中抽象方法,在使用Lambda时候,第一个参数是实例方法的调用者,第二个参数是实例方法的参数,那么可以使用方法引用。
@Test
public void test09(){
BiPredicate<String,String> bp1 = (x,y)-> x.equals(y);
BiPredicate<String,String> bp2 = String::equals;
}
构造函数引用
格式:
ClassName::new
**
package cn.unuuc.java8;
public class Person {
private Integer id;
private String name;
private Integer age;
public Person() {
}
public Person(Integer id) {
this.id = id;
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public Person(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
}
测试方法中,将通过构造器引用来实现对象的创建
// 无参数构造函数引用
@Test
public void test01(){
// Lambda表达式
Supplier<Person> sup = ()-> new Person();
// 构造器引用
Supplier<Person> sup2 = Person::new;
Person person = sup2.get();
}
// 1个参数构造函数引用
@Test
public void test02(){
// Lambda
Function<Integer,Person> fun = (x)-> new Person(x);
// 构造器引用
Function<Integer,Person> fun2 = Person::new;
Person apply = fun2.apply(1);
}
// 2个参数构造函数引用
@Test
public void test03(){
// Lambda
BiFunction<String,Integer,Person> biFun = (x,y)->new Person(x,y);
// 构造器引用
BiFunction<String,Integer,Person> biFun2 = Person::new;
Person chen = biFun2.apply("chen", 22);
}
总结:
构造器的引用要与函数接口中抽象方法参数列表要一致,这里的函数结构是可以自己定义的,不一定非要使用jdk自带的函数接口。
**
对于数组也是可以进行引用的
@Test
public void test04(){
// Lambda
Function<Integer,String[]> fun = (x)->new String[x];
// 构造器引用
Function<Integer,String[]> fun2 = String[]::new;
String[] strs = fun2.apply(20);
}