1.方法引用
方法引用的类型有四种形式:
(1)引用静态方法:类名称::static 方法名称 ;
(2)引用某个对象的方法:实例化对象 :: 普通方法 ;
(3)引用某个特定类的方法: 类名称 :: 普通方法 ;
(4)引用构造方法: 类名称 :: new 。
1.1引用静态方法
就相当于为方法起了个别名
package www.bit.java.testdemo;
@FunctionalInterface
// 是一个函数式编程接口,只允许有一个方法
//函数泛型接口
interface IUtil<P,R> {
public R switchPara(P p) ;
}
public class TestDemo {
public static void main(String[] args) {
//进行方法引用
// String valueOf类的静态方法
IUtil<Integer,String> iu = String :: valueOf ;
// 相当于调用了String.valueOf(1000)
String str = iu.switchPara(1000) ;
System.out.println(str.length());
}
}
1.2引用对象方法 y=f()
String中的toUpperCase()方法为对象方法
package www.bit.java.testdemo;
@FunctionalInterface // 是一个函数式编程接口,只允许有一个方法
interface IUtil {
public R switchPara() ;
}
public class TestDemo {
public static void main(String[] args) {
IUtil iu = “hello” :: toUpperCase ; // 进行方法引用
System.out.println(iu.switchPara()); // 转换的就是这个"hello"
}
}
1.3引用类中普通方法
类名::成员方法
String有一个compareTo成员方法,此方法为普通方法
package www.bit.java.testdemo;
@FunctionalInterface
// 是一个函数式编程接口,只允许有一个方法
interface IUtil<R,P> {
public R compare(P p1,P p2) ;
}
public class TestDemo {
public static void main(String[] args) {
IUtil<Integer,String> iu = String :: compareTo ;
System.out.println(iu.compare(“刘”, “霍”));
}
}
1.4 引用构造方法
类(x)–>函数接口(x)
package www.bit.java.testdemo;
class Person {
private String name ;
private int age ;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return “Person [name=” + name + “, age=” + age + “]”;
}
}
@FunctionalInterface // 是一个函数式编程接口,只允许有一个方法
interface IUtil<R,PN,PA> {
public R createPerson(PN p1,PA p2) ;
}
public class TestDemo {
public static void main(String[] args) {
IUtil<Person,String,Integer> iu = Person :: new;
// 相当于调用Person类的构造方法
System.out.println(iu.createPerson(“yuisama”, 25));
}
}