Java---方法引用(JDK1.8)

来源:互联网 发布:python画爱心 编辑:程序博客网 时间:2024/05/22 14:17

引用:对象引用,对象引用的本质在于为一个对象起别名,即:不同的栈内存可以同时指向同一块堆内存空间。
与对象引用类似的情况是,方法引用,即:为方法设置别名。


在JDK 1.8之中针对于方法引用提供有如下的四种形式:

· 引用静态方法:“类名称 :: static方法名称”;
· 引用某个对象的方法:“实例化对象 :: 普通方法”;
· 引用某个特定类的方法:“类名称 :: 普通方法”;
· 引用构造方法:“类名称 :: new”。


引用静态方法:

interface Demos<T>{    public void fun(T t);}public class Test {    public static void main(String[] args) {        Demos<String> demo = System.out :: println ;        demo.fun("Hello World!");    }}

引用某个对象的方法:

interface Demos<T>{    public T fun();}public class Test {    public static void main(String[] args) {        Demos<String> demo = "Hello World!" :: toUpperCase ;        System.out.println(demo.fun());    }

引用某个特定类的方法:

interface Demos<T,R>{    public R fun(T t1,T t2);}public class Test {    public static void main(String[] args) {        Demos<String,Boolean> demo = String :: equals ;        System.out.println(demo.fun("H

引用构造方法:

interface Demos<T,B,R>{    public R fun(T t,B b);}class Fruit{    private String name;    private double price;    public Fruit(String name, double price) {        super();        this.name = name;        this.price = price;    }    @Override    public String toString() {        return "Fruit [name=" + name + ", price=" + price + "]";    }}public class Test {    public static void main(String[] args) {        Demos<String,Double,Fruit> demo = Fruit :: new ;        System.out.println(demo.fun("西瓜",20.16));    }}
0 0