Java8学习笔记(三)--方法引入
基本概念
格式
实例变量名 | 类名 :: 静态方法 | 实例方法
作用
简化Lambda表达式
示例
a -> System.out.println(a);
<=> System.out::println
或
(a, b) -> a.compareTo(b);
<=> String::compareTo;
形式
方法引入总共有四种表现形式:
类型 | 示例 |
---|---|
引用静态方法 | ContainingClass::staticMethodName |
引用某个对象的实例方法 | containingObject::instanceMethodName |
引用某个类型的任意对象的实例方法 | ContainingType::methodName |
引用构造方法 | ClassName::new |
应用
POJO
public class Emp {
private int empno;
private String ename;
//其余方法略
}
引用静态方法####
@FunctionalInterface
public interface StaticMethod {
int min(int a, int b);
}
StaticMethod staticMethod = (a, b) -> Math.min(a,b);
StaticMethod staticMethod1 = Math::min;
引用某个对象的实例方法
@FunctionalInterface
public interface InstanceMethodOfParticularObject {
void setEmpName(String name);
}
Emp emp = new Emp(1,"eName");
//普通Lambda表达式
InstanceMethodOfParticularObject instanceMethodOfParticularObject = name -> emp.setEname(name);
instanceMethodOfParticularObject.setEmpName("haha");
System.out.println(emp.getEname());
//方法引入--引用某个对象的实例方法
InstanceMethodOfParticularObject instanceMethodOfParticularObject1 = emp::setEname;
instanceMethodOfParticularObject1.setEmpName("xixi");
System.out.println(emp.getEname());
引用某个类型的任意对象的实例方法
@FunctionalInterface
public interface InstanceMethodOfArbitraryObject {
boolean equale(String a,String b);
}
InstanceMethodOfArbitraryObject instanceMethodOfArbitraryObject = (a, b) -> a.equals(b);
InstanceMethodOfArbitraryObject instanceMethodOfArbitraryObject1 = String::equals;
System.out.println(instanceMethodOfArbitraryObject1.equale("a","b"));
System.out.println(instanceMethodOfArbitraryObject.equale("a","a"));
引用构造方法
@FunctionalInterface
public interface ConstructorWithFullFields {
Emp getNewEmp(int empno,String ename);
}
//无参构造
ConstructorWithNoField<Emp> constructorWithNoField = ()-> new Emp();
ConstructorWithNoField<Emp> constructorWithNoField1 = Emp::new;
//全参构造
ConstructorWithFullFields constructorWithFullFields = ((empno, ename) -> new Emp(empno,ename));
ConstructorWithFullFields constructorWithFullFields1 = Emp::new;
总结
- 一般情况下,用方法引入代替普通Lambda表达式均满足以下条件:
- 返回值类型相同
- 参数类型及个数相同
比如第1/2/4种形式。
- 第3种形式比较特殊,需满足以下条件:
- 返回值类型相同
- 两个参数
- 类型相同
因此会自动适配,否则会报错,如:
Non-Static method cannot be referenced from a static context
参考
God, Grant me the SERENITY, to accept the things I cannot change,
COURAGE to change the things I can, and the WISDOM to know the difference.