Reputation: 4473
I am new to Java annotation. I have used the following annotation in my Spring boot application as follows:
Original annotation definition:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
EntityType entityType();
ActionType actionType();
Resource resourceType();
}
Now I would like to move actionType()
and resourceType()
to a different annotation say MySubAnnotation
and use it in the original above annotation MyAnnotation
as follows:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
EntityType entityType();
MySubAnnotation mySubAnnotation();
}
But I am facing an issue with using this as follows:
@MyAnnotation(entityType = EntityType.MY_ENTITY,
mySubAnnotation = <???>) <---HERE I CANNOT UNDERSTAND WHAT TO SPECIFY
@MySubAnnotation(actionType=ActionType.UPDATE,
resourceType=Resource.MY_RESOURCE)
public void myMethod() {
...
}
As mentioned above, I cannot understand what to specify for sub annotation. Could anyone please help here? Thanks.
Upvotes: 0
Views: 1787
Reputation: 298113
You didn’t include the declaration of your MySubAnnotation
. Besides that, the syntax for the actual annotation values is not different for nested annotations. You just have to place it after the =
:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
EntityType entityType();
MySubAnnotation mySubAnnotation();
}
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface MySubAnnotation {
ActionType actionType();
Resource resourceType();
}
@MyAnnotation(
entityType = EntityType.MY_ENTITY,
mySubAnnotation = @MySubAnnotation(
actionType = ActionType.UPDATE,
resourceType = Resource.MY_RESOURCE
)
)
public void myMethod() {
}
Note that in this example, MySubAnnotation
has an empty list of targets, i.e. @Target({})
which permits it only as a value within other annotations. Of course, you could add other permitted targets. That would not affect its use as “sub annotation”, as that’s always allowed.
But there’s not much advantage in designing annotation parts as sub annotation here. All you’ve achieved, is requiring more typing. One imaginable possibility, is to provided a default here, e.g.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
EntityType entityType();
MySubAnnotation mySubAnnotation() default
@MySubAnnotation(actionType=ActionType.UPDATE, resourceType=Resource.MY_RESOURCE);
}
The difference to just specifying defaults for actionType
and resourceType
is that now, the developer may use the default for MySubAnnotation
, i.e. both values, or has to specify explicit values for both, they can not override only one of them.
Upvotes: 3