How does @FunctionalInterface affect the behavior of the JVM?

My original question was an exact duplicate of this ; that is, why this interface has a run-time retention policy.

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

  • the fact that this @Documented interface has (I believe) nothing to do with it (although why @Documented has a retention policy at runtime is also a mystery to me);
  • although many "will be" functional interfaces that existed in Java prior to Java 8 ( Comparable , as mentioned in the answer, but also Runnable , etc.), this does not prevent them from being used as "substitutions" (for example, you can use DirectoryStream.Filter as a replacement for Predicate if all you do is filter on Path , for example).

But still it has this retention. This means that it must somehow influence the behavior of the JVM. How?

+5
source share
2 answers

I found thread on the core-libs-dev mailing list which discusses saving @FunctionalInterface annotation. The highlight mentioned here is to allow third-party tools to use this information for code analysis / verification and to allow non-Java JVM languages ​​to correctly display their lambdas for functional interfaces. Some excerpts:

Joe Darcy (original committer @FunctionalInterface ):

We intentionally made this annotation by saving runtime, allowing it to also request various tools at runtime, etc.

Brian Goetz

There is an advantage for languages ​​other than Java, which can use this as a means to determine if the interface is suitable for switching to the SAM conversion engine. JDK support for lambda conversion is available for other languages.

It seems that it is not used by the JVM itself, it is just an additional feature for third-party tools. Creating visibility in annotations is not a big price, so there seems to be no good reason not to.

+4
source

The only requirement for annotations with retention policy runtime is

Annotations must be written to the class file by the compiler and saved by the VM at run time, so they can be read with reflexivity. ( https://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html#RUNTIME )

Now this has some implications for runtime behavior, since the class loader must load these annotations, and the virtual machine must store these annotations in memory for reflective access (for example, third-party libraries).

However, there is no requirement for a virtual machine to act on such annotations.

+1
source

Source: https://habr.com/ru/post/1243360/


All Articles