以下内容都属于Lambda表达式的补充。只有JDK1.8才可以使用。
最初引用基本上就是针对引用类型完成的(数组、类、接口具备引用的操作),现在追加了方法引用的概念。本质上就是别名,所以方法的引用就是别名的使用。
方法引用的类型可以有四种形式:
一、引用静态方法:类名称 :: static方法名称;
就相当于给方法起了一个名字。
代码示例:在String类中有一个valueof()方法,这个方法就是进行静态调用的。
@FunctionalInterface//表明这是一个函数式编程接口,只允许有一个方法
interface IMath<I,S>{
public S transform(I x);
}
public class TestDemo {
public static void main(String[] args) {
//函数式编程的使用
IMath<Integer,String> p=String :: valueOf;//进行方法引用
String str=p.transform(20);
System.out.println(str.length());
}
}
运行结果:
2
二、引用某个对象的方法:实例化对象 :: 普通方法;
代码示例:应用某一个对象中的方法
@FunctionalInterface//表明这是一个函数式编程接口,只允许有一个方法
interface IMath<S>{
public S transform();
}
public class TestDemo {
public static void main(String[] args) {
//函数式编程的使用
IMath<String> p="world" :: toUpperCase;//进行方法引用
//IMath<String> p=()->"world" .toUpperCase();//Lambda表达式
System.out.println(p.transform());
}
}
运行结果:
WORLD
三、引用某个特定类的方法:类名称 :: 普通方法;
代码示例:String类中有一个compareTo(),进行比较大小
@FunctionalInterface//表明这是一个函数式编程接口,只允许有一个方法
interface IMath<I,S>{
public I compare(S p1,S p2);
}
public class TestDemo {
public static void main(String[] args) {
IMath<Integer,String> p=String::compareTo;//进行方法引用
System.out.println(p.compare("a","A"));
}
}
运行结果:
32
四、引用构造方法:类名称 ::new。
代码示例:
class Person{
private String name;
private int age;
public Person(String name,int age) {
this.name=name;
this.age=age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
@FunctionalInterface//表明这是一个函数式编程接口,只允许有一个方法
interface IMath<P,S1,S2>{
public P create(S1 p1,S2 p2);
}
public class TestDemo {
public static void main(String[] args) {
IMath<Person,String,Integer> p=Person::new;//进行方法引用
System.out.println(p.create("张三",20));
}
}
运行结果:
Person [name=张三, age=20]