java interface源码,Java源码之@FunctionalInterface

Javadoc解释

An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.

在Java语言的规范下,这是一个标识性质的注解,用来表示这个接口将用作函数式接口。

Conceptually, a functional interface has exactly one abstract method. Since {@linkplain java.lang.reflect.Method#isDefault() default methods} have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of {@code java.lang.Object}, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from {@code java.lang.Object} or elsewhere.

从概念上来说,一个函数式接口只能有一个抽象方法。因为Method当中的isDefault()已经有一个实现,而且它们不是抽象的。如果一个被接口声明的抽象方法重写了Object的一个公共方法,那么它也不计算到接口抽象方法,因为接口的任何实现都会来自Object或者其他地方的实现。

Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

注意,函数式接口的实例可以通过lambda表达式、方法引用或构造函数引用创建。

If a type is annotated with this annotation type, compilers are required to generate an error message unless:

1.The type is an interface type and not an annotation type, enum, or class.

2.The annotated type satisfies the requirements of a functional interface.

如果一个类声明了该注解,那么编译器需要产生一个错误信息,除非:

1. 该注解只能修饰接口类型,不能写在注解、枚举或者普通的Java类。

2. 带注解的类需要满足函数式接口的要求。

However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a {@code FunctionalInterface} annotation is present on the interface declaration.

然而,无论接口声明中是否存在FunctionalInterface注释,编译器都会将满足函数式接口定义的任何接口视为函数式接口。

代码测试

声明的接口只能有一个抽象方法

// 声明FunctionalInterface

@FunctionalInterface

public interface IFunc {

// 需要执行的方法

void execute();

}

复制代码

测试运行

public static void main(String[] args) {

((IFunc)() -> {

System.out.println("IFunc execute!");

}).execute();

}

复制代码

当然,如果打破规范,声明两个抽象方法

@FunctionalInterface

public interface IFunc {

// 需要执行的方法

void execute();

// 打破规范

void breakRule();

}

复制代码

在Eclipse当中会引起编译问题

562e4938e9a2ed96f294bcfb85b809e0.png

在IDEA当中也会引起编译问题

0fda3268412f6a76ab18a3daa74e3e8a.png

而当我们声明Object的抽象方法,也是符合语法规范

@FunctionalInterface

public interface IFunc {

// 需要执行的方法

void execute();

// 重写Object的抽象方法

boolean equals(Object obj);

}

复制代码

总结

这只是一个标识性质的注解,但是也不会影响使用lambda函数式编程,不会硬性要求,就跟@Override一样。

带上了这个注解,那么编译器就会语法校验。在Java语言规范下只能有一个抽象方法,当然重写Object的方法除外。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值