上一次介绍了Java8新特性中的Lambda表达式,现在继续讲解Java8的新特性之二:
方法引用:方法引用其实也离不开Lambda表达式。
方法引用的类型
类型 | 对应Lambda表达式 | 语法 |
---|---|---|
静态方法引用 | (args) -> 类名.static_Method(args) | 类名::staticMethod |
对象方法引用 | (inst,args) -> 类名.inst_Method(args) | 类名::instMethod |
实例方法引用 | (args) -> inst.inst_Method(args) | inst::instMethod |
构建方法引用 | (args) -> new 类名(args) | 类名::new |
方法引用举例
/**
* JDK8新特性之方法引用
*/
public class Demo6 {
//类型 语法 对应lambda表达式
//构造器引用 Class::new (args) -> new 类名(args)
//静态方法引用 Class::static_method (args) -> 类名.static_method(args)
//对象方法引用 Class::method (inst,args) -> 类名.method(args)
//实例方法引用 instance::method (args) -> instance.method(args)
/**
*对象方法引用
* 对象::method
*/
@Test
public void test01(){
List<String> wordsList = GetListData.wordsList;
//上一章提到的
//wordsList.forEach(s-> System.out.println(s));
//wordsList.forEach(System.out::println);
Date date = new Date();
/*long time = date.getTime();
System.out.println(time);*/
//返回一个毫秒数的时间戳 1970-现在的毫秒数
//进行对象方法引用之后
Supplier<Long> getTime = date::getTime;
Long aLong = getTime.get();
System.out.println(aLong);
}
/**
* 类名::静态方法
*/
@Test
public void test02(){
Supplier<Long> currentTimeMillis = System::currentTimeMillis;
System.out.println(currentTimeMillis.get());
}
/**
* 类名::实例方法
*/
@Test
public void test03(){
//
Function<String,Integer> length = String::length;
System.out.println(length.apply("helloworld"));
}
@Test
public void test04(){
Supplier<Student> student = Student::new;
Student student1 = student.get();
student1.setName("ange");
student1.setAge(18);
System.out.println(student1);
}
}
嗯,还是这么简单,依旧是将代码简化
继续装逼