@FunctionalInterface注解以及测试示例

    技术2022-08-01  81

    该注解用来注解函数接口。函数接口(Functional Intelface)是一个有且只有一个抽象方法的接口,可以有多个静态方法。

    1. 自定义示例

    1.1 自定义函数接口

        该函数接口有且只有一个抽象方法,一个成员变量(默认被final static修饰),多个静态方法,且可在方法内引用其他自定义类。

    @FunctionalInterface interface Student{ String name="Jerome"; // 默认被final static修饰 void study(); // 抽象方法 static void goSchool(){ System.out.println("Going school."); } static void singIn(){ System.out.println(name); } static void getJob(){ Staff staff = new Staff(); //自定义类 staff.setName(name); } } // 准备测试的用例类 class Teacher { static void teach(Student student){ student.study(); // 调用函数接口Student的抽象方法 } }

    1.2 测试用例

    @Test void functionalInterfaceTest(){ Student.goSchool(); Student.singIn(); Teacher.teach(()->System.out.println("Student is studying.")); // lambda实现函数接口的study 抽象方法 }

    结果打印


    Going school. Jerome Student is studying.


    2. 内置行数接口

    java.lang.Runnable java.util.concurrent.Callable java.util.function.Perdicate

        ...

    Processed: 0.009, SQL: 9