java8 新特性2
方法引用
我们用Lambda表达式来实现匿名方法,但有些时候我们使用Lambda表达式仅仅是调用一些已经存在的方法,处理调用动作外,没有其他动作。这种情况下我们更倾向于通过方法名来调用它,而Lambda表达式可以帮我们实现这一要求。它使得Lambda在调用那些已经拥有方法名的方法的代码更加方便简洁。方法引用可以理解为Lambda表达式的另一种表现形式。
方法的引用使用一对冒号::
理解
方法引用的根本,是对Lambda 表达式的进一步简化和省略。
方法引用的分类
- 静态方法引用 类名::staticMethod
- 实例方法引用 inst::instMethod
- 对象方法引用 类名::instMethod
- 构建方法引用 类名::new
静态方法引入
interface Hello{
public void say();
}
class test{
public static void show(){
System.out.println("hello");
}
public static void main(String[] args) {
Hello h = test::show;
h.say();
Hello h1 = ()->test.show();
h1.say();
}
}
也就是通过已有的静态方法去实现接口方法。
实例方法引用
class Person{
public void personSay(){
System.out.println("hello");
}
}
interface Hello{
public void say();
}
public class test {
public static void main(String[] args) {
Person person = new Person();
Hello h2 = person::personSay;
h2.say();
Hello h3 = ()-> person.personSay();
h3.say();
}
}
首先实例对象,在通过对象名访问对象内方法,实现接口方法
对象方法引用
public class test {
public static void main(String[] args) {
StringControl str = new StringControl() {
@Override
public boolean isEqual(String x,String y) {
return x.equals(y);
}
};
StringControl st = (String x,String y)->x.equals(y);
StringControl s = String::equals;
System.out.println(str.isEqual("a","a"));
System.out.println(st.isEqual("a","a"));
System.out.println(s.isEqual("a","a"));
}
}
interface StringControl{
public boolean isEqual(String x,String y);
}
当一个接口只有一个方法,该方法的实现包含 x.方法名(y)
,可以进行缩写
构造方法引用
public class Student {
private int age;
private String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public void say(){ }
}
class Boy extends Student{
public Boy(int age, String name) {
super(age, name);
}
@Override
public void say() {
System.out.println("hello");
}
}
interface StudentCreate<T extends Student>{
public T create(int age,String name);
}
public class run {
public static void main(String[] args) {
StudentCreate studentCreate = new StudentCreate() {
@Override
public Student create(int age,String name) {
return new Boy(age,name);
}
};
StudentCreate stu = (int age,String name)->new Boy(age,name);
StudentCreate s = Boy::new;
Boy boy = (Boy) studentCreate.create(12,"zs");
boy.say();
Boy boy2 = (Boy) stu.create(13, "lisi");
boy2.say();
Boy boy3 = (Boy) s.create(14, "wangwu");
boy3.say();
}
}
一种实现构造的方式,就当前来看,外在代码减少了,但也变复杂了一些?