Would lambda expressions be meaningful annotation properties?

Rafael Winterhalter rafael.wth at gmail.com
Mon May 10 21:40:01 UTC 2021


Hello, I was wondering if there was ever any consideration of allowing
(stateless) lambda expressions as annotation members. As an example, this
would make the following lambda expression possible:

@interface MyAnnotation {
  Supplier<String> value();
}

In many enterprise applications, this would be a very helpful addition and
replace a rather complicated pattern with little type-safety. For example,
in Spring, beans can be registered conditionally. Today, this requires
declaring a class that implements the Condition interface which then can be
supplied as an argument to the Conditional annotation:

public class MyCondition implements Condition {
  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata
metadata) {
    return MyCode.isEnabled(context, metadata)
  }
}

which is then used in:

@Conditional(MyCondition.class) @Bean
public MyBean myBean() { ... }

By allowing stateless lambda expressions as annotation members, this could
be simplified to:

@Conditional(MyCode::isEnabled) @Bean
public MyBean myBean() { ... }

Another example where this would improve code readability a lot would be
bean validation frameworks, where custom constraints could be moved
directly to a property:

class MyBean {
  @Valid(value -> value != null && MyCode.validate(value))
  String property;
}

I observe such patterns regularly and therefore, I was curious if such a
feature was ever discussed or if this would be considered for a future
version. I understand that the intention of annotations is to provide
declarative metadata which can be processed also for unloaded code, but I
still feel like this would be a useful extension. The lambda expression
would be implicitly stateless, but of course they represent code that
requires class loading and would therefore be not necessarily meaningful to
annotation processors or other static code processing tools. If this would
be a feature to consider and only not a priority, I would be happy to
contribute, given I could get some help around the formalities of such a
process.

Thanks, Rafael


More information about the core-libs-dev mailing list