5

Is it possible in Java to store an annotation value in a constant field (or similar) to reuse it on each method where is needed? For example if I have this annotated method:

@CustomAnnotations({
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    ...
    @CustomAnnotation(..)
})
private static MyReturnValue doSomething(){
    ..
}

and I want to add the identical annotation to many methods in the same class without cut and paste it for each one, is it possible to define a field like:

private static final Something annotationsConstant = {
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    ...
    @CustomAnnotation(..)
}

@CustomAnnotatins(annotationsConstant)    
private static MyReturnValue doSomething(){
    ..
}

@CustomAnnotatins(annotationsConstant)    
private static MyReturnValue anotherMethod(){
    ..
}

If yes what is the dataType of the field containing the annotations? If not is there another way to that without rewrite for each method the same annotation?

user2572526
  • 1,219
  • 2
  • 17
  • 35

1 Answers1

6

It sounds like you want one annotation to extend other annotations. Sadly, this is not possible in Java. e.g. See this question.

However, there are ways to achieve something similar. Try researching how Spring compose annotations.

Community
  • 1
  • 1
whistling_marmot
  • 3,561
  • 3
  • 25
  • 39