I have two annotations from a framework. Often I use those two annotations both on the same field. Thus I'm trying to create a "combined" annotation that contains that both two.
But I don't know if it is possible at all:
The existing annotations (that I have no control of):
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiParam {
String name() default "";
}
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiModelProperty {
String name() default "";
}
My Custom annotation that I'm trying to create:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
@ApiParam
@ApiModelProperty
public @interface SwaggerParam {
String name() default "";
}
Result: the annotations are not applicable to annotation type.
Question: Is there any chance?
It is possible to merge two annotations on an independent tier into one annotation. To do so, select the first annotation of the two you want to merge. Then either right click in the Timeline Viewer or click Annotation in the ELAN main menu and select Merge with Next Annotation.
It is also possible to use multiple annotations on the same declaration: @Author(name = "Jane Doe") @EBook class MyClass { ... } If the annotations have the same type, then this is called a repeating annotation: @Author(name = "Jane Doe") @Author(name = "John Smith") class MyClass { ... }
You can repeat an annotation anywhere that you would use a standard annotation.
Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it.
Unfortunately you can't do this since it is not possible to extend annotations.
Is there something like Annotation Inheritance in java?
When I first answered this I was initially confused by the Spring framework approach to this shortcoming whereby they use meta level annotations (such as @Component as a meta annotation for @Controller/@Configuration etc.) as a sort of workaround.
See: https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-annotation-config
Composing annotations like you did can only be done if your framework supports scanning for meta-annotations. Thus the framework not only has to scan for direct annotations but also for an annotation's meta-annotations recursively.
Multiple frameworks support this, some of which are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With