引用的本质是别名,方法引用也是别名的使用。方法引用有一下4种
1)引用静态方法: 类名称::static 方法
2)引用某个对象的方法: 实例化对象::普通方法
3)引用某个特定类的方法: 类名称::普通方法
4)引用构造方法: 类名称::new
这四种方法引用都应该结合函数接接口实现(这些是lambda的补充)
引用静态方法:
String类中有一个static String valueof()方法,这个方法就是进行静态调用。
/**
* 引用静态方法
* @param <P>
* @param <R>
*/
@FunctionalInterface
interface IUtil<P,R>{
public R exchange(P p);
}
public class TestDemo {
public static void main(String [] args){
IUtil<Integer,String> iu = String::valueOf; //进行方法引用
String str = iu.exchange(1000); //相当于:String.valueof(1000)
System.out.println(str.length());
}
}
引用某一个对象中的方法:
/**
* 引用某一个对象中的方法
* @param <R>
*/
@FunctionalInterface
interface IUtil<R>{
public R exchange();
}
public class TestDemo {
public static void main(String [] args){
IUtil<String> iu = "chinese"::toUpperCase; //引用某一个对象中的方法
System.out.println(iu.exchange());
}
}
引用某个特定类的方法:
@FunctionalInterface
interface IUtil<R,P>{
public R compare(P p1, P p2);
}
public class TestDemo{
public static void main(String [] argc){
IUtil<Integer,String> iu = String::compareTo;
System.out.println(iu.compare("S","s"));
}
}
引用构造方法:
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 IUtil<R,FP,SP>{
public R create(FP p1,SP p2);
}
public class TestDemo{
public static void main(String [] args){
IUtil<Person,String,Integer> iu = Person::new;
System.out.println(iu.create("张三",20));
}
}
上述引用作为lambda表达式的扩展感觉用处不大,了解即可。