Feature request: custom default annotation attributes

Rob Spoor openjdk at icemanx.nl
Sun Nov 21 17:17:23 UTC 2021


Hi all,

I've been writing a few annotations lately that have one required 
attribute and some optional ones. That leaves me with three options:

1) Use value() for the required attribute. That becomes ugly when the 
optional attributes are given though.
2) Make developers write the attribute name every time. This is 
currently my choice.
3) Add the required attribute twice: once as value(), and once with a 
nice name. That adds complexity to annotation processing, and allows two 
different values for the same conceptual field.

I also know that I'm not the first one to encounter this issue. Spring 
is full of cases like this, and they've chosen the third option. For 
instance, RequestMapping.path[1] is an alias for value() (it's even 
annotated as such).

Now I was thinking: wouldn't it be nice to be able to define a custom 
default attribute? That could be done using an annotation, let's call it 
@DefaultAttribute. For this annotation the following rules would apply:
1) It can only be applied to annotation attributes. That means it gets 
special compiler support; that's also true for @Override though.
2) If value() is present, that is the default attribute automatically 
(like it is now).
3) It's a compiler error to have more than one default attribute, 
including value().

For users of the annotation, the same rules would apply as for value(): 
a single attribute value may be given without the name if there is a 
default attribute, either value() or an explicit one.

If we apply this to RequestMapping, the value() attribute could be 
dropped (in a new major version):

     @interface RequestMapping {
         @DefaultAttribute String[] path() default {};
         // name, method, params, headers, consumes, produces as-is
     }

Used: @RequestMapping("/test") // .path() now returns "/test"


Any thoughts?

Rob


[1] 
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html#path--


More information about the core-libs-dev mailing list