How does @FunctionalInterface influence the JVM's runtime behavior?

自闭症网瘾萝莉.ら 提交于 2020-01-02 04:27:08

问题


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:

  • 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).

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


回答1:


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 (original committer of @FunctionalInterface):

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

Brian Goetz

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.

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.




回答2:


The only requirement for annotations with retention policy runtime is

Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively. (https://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html#RUNTIME)

Now this has some consequences on runtime behaviour, since the class loader must load these annoations and the VM must keep these annotations in memory for reflective access (for example by third party libraries).

There is however no requirement for the VM to act on such annotations.



来源:https://stackoverflow.com/questions/35496105/how-does-functionalinterface-influence-the-jvms-runtime-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!