@FunctionalInterface 如何影响 JVM 的运行时行为? [英] How does @FunctionalInterface influence the JVM's runtime behavior?

查看:19
本文介绍了@FunctionalInterface 如何影响 JVM 的运行时行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最初的问题是这个问题的完全重复;也就是说,为什么这个接口有运行时保留策略.

My initial question was an exact duplicate of this one; that is, why is it that this interface has a runtime retention policy.

但是接受的答案根本不让我满意,原因有两个:

But the accepted answer does not satisfy me at all, for two reasons:

  • 这个接口是 @Documented 的事实(我相信)与它无关(尽管为什么 @Documented 有运行时保留策略对我来说是个谜以及);
  • 尽管在 Java 8 之前的 Java 中存在许多可能是"的函数式接口(Comparable 作为答案提到,还有 Runnable 等),但这并不能阻止它们不会被用作替代品"(例如,你可以完美地使用 DirectoryStream.Filter 代替 Predicate>路径,例如).
  • the fact that this interface is @Documented has (I believe) nothing to do with it (although why @Documented has a runtime retention policy is a mystery to me as well);
  • even though many "would be" functional interfaces existed in Java prior to Java 8 (Comparable as the answer mentions, but also Runnable etc), this does not prevent them from being used as "substitutes" (for instance, you can perfecty well use a DirectoryStream.Filter as a substitute to a Predicate if all you do is filter on Path, for instance).

但是,它仍然具有这种保留能力.这意味着它必须以某种方式影响 JVM 行为.怎么样?

But still, it has this retention. Which means that it has to influence the JVM behavior somehow. How?

推荐答案

我找到了 thread 在 core-libs-dev 邮件列表中,讨论了 @FunctionalInterface 注释的保留.这里提到的要点是允许第三方工具使用此信息进行代码分析/验证,并允许非 Java JVM 语言将其 lambda 正确映射到功能接口.部分摘录:

I've found the thread in core-libs-dev mailing list which discusses the retention of @FunctionalInterface annotation. The main point mentioned here is to allow third-party tools to use this information for code analysis/validation and to allow non-Java JVM languages to map correctly their lambdas to functional interfaces. Some excerpts:

Joe Darcy(@FunctionalInterface 的原始提交者):

我们故意让这个注解有运行时保留允许它也可以在运行时向各种工具查询,等等.

We intentionally made this annotation have runtime retention to allow it to also be queried to various tools at runtime, etc.

布莱恩·戈茨

Java 之外的语言有一个优势,可以使用它作为一种手段来确定接口是否适合传递给 SAM 转换机制.JDK 对 lambda 转换的支持也可用于其他语言.

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本身并没有使用它,它只是第三方工具的额外可能性.使注释运行时可见并不是一个很大的成本,所以似乎没有充分的理由不这样做.

So seems that it's not used by JVM itself, it's just an additional possibility for third-party tools. Making the annotation runtime-visible is not a big cost, so seems there were no strong reasons not to do this.

这篇关于@FunctionalInterface 如何影响 JVM 的运行时行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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