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.");
}
}