Java深入-方法引用

      大纲:

       一、Java中函数引用介绍   

        二、函数引用范例

    

      Java中函数引用介绍

      函数引用是在JDK1.8中提出的,函数引用就是一个方法可以被多个不同方法名称所描述。要想实现这一操作,Java中提供了四种方法的引用格式。

      1、引用静态方法:      类名称 :: 静态方法

      2、引用实例化对象方法:     实例化对象 :: 普通方法

      3、引用特定类型的方法:     特定类 :: 普通方法

      4、引用构造方法:           类名称 :: new

      

      函数引用范例

package cn.txp.lambda;
/**
 * @param <P> 表示参数类型
 * @param <R> 表示返回结果类型
 */
@FunctionalInterface
interface IFunction<P, R>{
    R change(P p);
}
public class FunAdducation {
    public static void main(String[] args) {
        // 引用String类提供的静态方法 valueOf();
        IFunction<Integer, String> ifun = String :: valueOf;
        System.out.println(ifun.change(500).getClass().getName()); // 返回结果:   java.lang.String
    }
}
package cn.txp.lambda;
/**
 * @param <R> 表示返回结果类型
 */
@FunctionalInterface
interface IFunction<R>{
    R upper();
}
public class FunAdducation {
    public static void main(String[] args) {
        // 引用实例化方法, 字符串是String的匿名对象
        IFunction<String> ifun = "to upper str" :: toUpperCase;
        System.out.println(ifun.upper()); // 返回结果:   TO UPPER STR
    }
}

 

package cn.txp.lambda;
/**
 * @param <R> 表示返回结果类型
 */
@FunctionalInterface
interface IFunction<P, R>{
    R compare(P p1, P p2);
}
public class FunAdducation {
    public static void main(String[] args) {
        // 引用特定类,如果不想使用实例化对象来引用,而只想引用这个方法,可以使用特定类引用
        IFunction<String, Integer> ifun = String :: compareTo;
        System.out.println(ifun.compare("T", "t")); // 返回结果:  -32
    }
}

 

package cn.txp.lambda;
class Dog{
    private String name;
    private Integer age;
    public Dog(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "名称:" + this.name + "\t" + "年龄:" + this.age;
    }
}
/**
 * @param <R> 表示返回结果类型
 */
@FunctionalInterface
interface IFunction<R>{
    R create_dog(String name,  Integer age);
}
public class FunAdducation {
    public static void main(String[] args) {
        // 引用构造方方法
        IFunction<Dog> ifun = Dog :: new;
        System.out.println(ifun.create_dog("狗蛋", 5)); // 返回结果:  名称:狗蛋    年龄:5
    }
}

 

 

 

 

     知乎文章: https://www.zhihu.com/people/tan-xu-peng-44


    编程专业知识:https://www.cnblogs.com/tjava


    编程开发技术问题解决CSDN:https://blog.csdn.net/qq_37291829

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

      

      

posted @ 2020-09-16 11:11  谭旭鹏  阅读(342)  评论(0)    收藏  举报