注解:@FunctionalInterface函数式接口

@FunctionalInterface 是 Java 8 引入的一个标记型注解,用于声明一个接口是函数式接口(Functional Interface)。函数式接口是指只有一个抽象方法的接口,这样的接口可以被用作 Lambda 表达式的类型。使用 @FunctionalInterface 注解有助于确保接口符合函数式接口的定义,并且在编译时如果接口包含多于一个抽象方法,编译器会报错。

以下是 @FunctionalInterface 注解的一些使用场景和要点:

基本用法

@FunctionalInterface
public interface MyFunctionalInterface {
    void doSomething(String input);
}

在这个例子中,MyFunctionalInterface 被声明为一个函数式接口,它有一个抽象方法 doSomething

使用 Lambda 表达式

由于 MyFunctionalInterface 是函数式接口,你可以使用 Lambda 表达式来实例化它:

MyFunctionalInterface instance = (String input) -> {
    System.out.println("Doing something with: " + input);
};

允许有多个非抽象方法

函数式接口可以有多个非抽象方法(默认方法),除了一个抽象方法之外:

@FunctionalInterface
public interface MyFunctionalInterface {
    void doSomething(String input);

    default void defaultMethod() {
        System.out.println("This is a default method.");
    }
}

与 Lambda 表达式一起使用

你可以在需要函数式接口的地方直接使用 Lambda 表达式:

public void execute(MyFunctionalInterface function) {
    function.doSomething("Hello");
}

// 使用 Lambda 表达式调用 execute 方法
execute((String input) -> System.out.println("Doing something with: " + input));

编译时检查

如果你的函数式接口不小心包含了多个抽象方法,使用 @FunctionalInterface 注解可以在编译时检查出来:

@FunctionalInterface
public interface MyFunctionalInterface {
    void doSomething(String input);
    void doAnotherThing(String input); // 这会导致编译错误
}

上面的代码会因为包含多个抽象方法而编译失败。

与方法引用一起使用

函数式接口也可以与方法引用一起使用:

MyFunctionalInterface instance = System.out::println;

这里,System.out::println 是一个方法引用,它引用了 PrintStream 类的 println 方法,并且这个引用符合 MyFunctionalInterface 接口的签名。

@FunctionalInterface 注解是 Java 8 函数式编程的一个重要组成部分,它使得接口可以更灵活地与 Lambda 表达式和方法引用一起使用,同时也提供了编译时的安全性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值