JAVA 自定义函数式编程

PS: 因想提取重复代码,所以寻求方案,最终确认使用函数式编程。但百度查下大部分写的是内置类用新版的函数式接口怎么实现(Consumer  Function Predicate);

1. 创建一个springboot项目

2.定义一个普通接口(TestInterface.java)

          2.1)类上注明为函数式接口(@FunctionalInterface), 有且只能有一个方法;

          2.2)定义接口 void testInterface(String str);

package com.inte;

@FunctionalInterface
public interface TestInterface {
    void testInterface(String str);
}

3. 定义一个普通Java类(Test.java)

package com.inte;

/**
 * @author :于志强
 * @date :Created in 2019/9/6 15:02
 * @description:测试函数式接口
 */
public class Test {
    public static void main(String[] args) {
        // fun 随便起个名字
        test("test function interface;", fun -> {
            System.out.println("test press...");
        });
    }

    /**
     * 测试接口
     * @param str 传的参数
     * @param testInterface 接口名字
     */
    public static void test(String str, TestInterface testInterface) {
        System.out.println("test begin...");
        testInterface.testInterface(str);
        System.out.println("test end.");
    }
}

------------------------------------------------------- 分割线 以上为单参数无返回值  --------------------------------------------------------------------

多入参+出参

4. 定义一个普通接口(MultiParameterInterface.java)

package com.inte;

@FunctionalInterface
public interface MultiParameterInterface {
    String testMultiParameter(String str1, String str2);
}

5. 继续使用Test.java

package com.inte;

/**
 * @author :于志强
 * @date :Created in 2019/9/6 15:02
 * @description:测试函数式接口
 */
public class Test {
    public static void main(String[] args) {
        // fun 随便起个名字
        test("test function interface;", fun -> {
            System.out.println("test press...");
        });
        System.out.println("-------------------------------- 分割线 --------------------------------------");

        // 多参数加返回值
        testMulti("第一个参数,", "第二个参数;", (str1, str2) -> {
            // 写逻辑处理...
            return str1 + str2 ;
        });
    }

    /**
     * 测试接口
     * @param str 传的参数
     * @param testInterface 接口名字
     */
    public static void test(String str, TestInterface testInterface) {
        System.out.println("test begin...");
        testInterface.testInterface(str);
        System.out.println("test end.");
    }

    /**
     * 测试接口
     * @param str1 传的参数
     * @param str2 传的参数
     * @param multiParameterInterface 接口名字
     */
    public static void testMulti(String str1, String str2, MultiParameterInterface multiParameterInterface) {
        System.out.println("multi begin...");
        String str = multiParameterInterface.testMultiParameter(str1, str2); // 接值
        System.out.println(str);
        System.out.println("multi end.");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值