为何FunctionalInterface的保留策略是RetentionPolicy.RUNTIME而非CLASS?
@FunctionalInterface annotated with RetentionPolicy.RUNTIME instead of RetentionPolicy.CLASS? Great question! At first glance, it might seem like @FunctionalInterface only exists for compile-time checks—after all, its primary job is to enforce that an interface has exactly one abstract method (excluding static and default methods). But there's more to it than that, which is why the retention policy is set to RUNTIME. Let's break down the key reasons:
Runtime frameworks and reflection rely on this metadata
Many popular Java frameworks (like Spring, Guava, or reactive libraries) use reflection at runtime to interact with types. For example, a framework might dynamically generate a proxy for a functional interface, or validate that a method reference is compatible with a functional interface. If@FunctionalInterfaceonly persisted up to theCLASSphase, these frameworks wouldn't be able to detect the annotation at runtime, breaking logic that depends on explicitly identifying functional interfaces.Lambda handling and runtime tooling benefit from it
While the compiler checks Lambda compatibility at compile time, the JVM and runtime tools still gain value from having this annotation available. Debuggers, profilers, and code analysis tools use runtime metadata to provide better insights—like highlighting Lambda-compatible interfaces or verifying that dynamic method dispatch works correctly for Lambda instances. WithoutRUNTIMEretention, these tools would lose a key piece of context about the interface's intended use.Third-party tools need runtime access to the annotation
Beyond core Java, developer tools like documentation generators, static analyzers, or testing frameworks scan classes at runtime to gather information.@FunctionalInterfaceacts as a clear signal that an interface is designed for Lambdas or method references. If the annotation was only present in the class file but not accessible at runtime, these tools couldn't leverage this signal to provide tailored features or validations.
It’s worth noting that RetentionPolicy.CLASS would be enough for basic compile-time checks, but Java’s designers chose RUNTIME to unlock all the runtime use cases that depend on explicitly recognizing functional interfaces. This makes the annotation far more useful than just a compile-time guard.
内容的提问来源于stack exchange,提问作者Rahul

