问题
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 alsoRunnable
etc), this does not prevent them from being used as "substitutes" (for instance, you can perfecty well use aDirectoryStream.Filter
as a substitute to aPredicate
if all you do is filter onPath
, 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