为什么在Java 8中使用@FunctionalInterface批注 [英] Why to use @FunctionalInterface annotation in Java 8

查看:305
本文介绍了为什么在Java 8中使用@FunctionalInterface批注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们的接口中仅包含一种抽象方法,则默认情况下为功能接口".任何人都可以解释@FunctionalInterface注释带来的其他好处吗?

If we have Interface with only one abstract method in it, it is by default Functional Interface. Can anyone please explain what additional advantage @FunctionalInterface annotation brings?

我知道,如果我们添加@FunctionalAnnotation,它将不允许某人在接口中添加另一个抽象方法,因为这会产生编译错误,但是我的意思是,即使您不使用@FucntionalInterface注释,同样,如果有人添加另一个抽象方法,它将破坏代码中所有现有的lambda表达式,并且编译器会抱怨.

I know that if we add @FunctionalAnnotation, it will not allow someone to add another abstract method in the interface, as it will give a compilation error, but my point is even if you don't use @FucntionalInterface annotation, then also, if someone will add another abstract method, it will break all the existing lambda expressions in the code and compiler will complain.

例如:

如果我具有以下界面:

public interface User {

    Integer fetchData(Integer userId);
}

具有以下实现方式:

public class UserImpl implements User{

    @Override
    public Integer fetchData(Integer userId) {
        return 1;
    }
}

及以下用法:

公共类TestFunctionalInterface {

public class TestFunctionalInterface {

public static void main(String[] args) {
    User user = a -> a*2;
    System.out.println("FetchedData:"+user.fetchData(2));
}

}

现在,如果我尝试在如下所示的界面中添加另一种方法:

And now,if I try to add another method in the interface like below :

public interface User {

    Integer fetchData(Integer userId);

    Integer fetchLoginDetails(Integer userId);

}

编译器在下面的代码中抱怨:

Compiler is complaining in below code :

public class TestFunctionalInterface {

    public static void main(String[] args) {
        User user = a -> a*2;
        System.out.println("FetchedData:"+user.fetchData(2));
    }

}

在线用户user = a-> a * 2;

at line User user = a -> a*2;

显示消息此表达式的目标类型必须是函数 界面".

With message "The target type of this expression must be a functional interface".

推荐答案

通过@functionalInterface保护界面的主要优点是使用lambda实例化它们时.

The main advantage to protect your interface by @functionalInterface is when you use lambda to instantiate them .

Lambda声明只能声明一个代码块,因此,如果您的接口上没有任何保护,而有些人会添加一个抽象方法,则您的lambda将不再有意义...

Lambda declaration can only declare one bloc of code so if there is no protection on your interface and some will add an abstract method your lambda have no more sense ...

为何强烈建议不要使用lambda实现某些隐式功能接口.

that why its highly recommend to not implement with lambda some implicit functional interface.

因此,如果您想通过lambda方式实现此接口,我建议您添加一个安全的注释.

So if you want to implement this interface by lambda way I encourage you to add the annotation that s a security. if you don't want this kind of implementation or if your interface will change or have an night risk to change don t had it

这篇关于为什么在Java 8中使用@FunctionalInterface批注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆