我最初的问题与 this one 完全相同;也就是说,为什么这个接口(interface)有运行时保留策略。
但是接受的答案根本不让我满意,原因有二:
- 这个接口(interface)是
@Documented
的事实(我相信)与它无关(尽管为什么@Documented
有运行时保留策略对我来说是个谜以及); - 即使在 Java 8 之前的 Java 中存在许多“将是”函数式接口(interface)(答案提到的
Comparable
,还有Runnable
等),但这并不能阻止它们不会被用作“替代品”(例如,如果您所做的只是过滤路径
,例如)。
但是,它仍然具有这种保留。这意味着它必须以某种方式影响 JVM 行为。怎么办?
最佳答案
我找到了 thread在讨论保留 @FunctionalInterface
注释的 core-libs-dev 邮件列表中。这里提到的要点是允许第三方工具使用这些信息进行代码分析/验证,并允许非 Java JVM 语言将它们的 lambda 正确映射到功能接口(interface)。部分摘录:
Joe Darcy(@FunctionalInterface
的原始提交者):
We intentionally made this annotation have runtime retention to allow it to also be queried to various tools at runtime, etc.
布赖恩·戈茨
There is a benefit for languages other than Java, that can use this as a means to determine whether the interface is suitable for passing to the SAM conversion machinery. The JDK support for lambda conversion is available to other languages as well.
看来JVM本身并没有使用它,它只是第三方工具的一种额外的可能性。使注释在运行时可见的成本并不高,因此似乎没有充分的理由不这样做。
关于java - @FunctionalInterface 如何影响 JVM 的运行时行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35496105/