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

查看:158
本文介绍了@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 作为谓词的替代,如果您只是在路径,例如)。

  • 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 讨论了 @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.

Brian Goetz


语言其他比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天全站免登陆