0

I have one parametrized annotation (@MiTag1 in this case). And I want to create a new annotation (@MiTag2), that extends @MiTag1 and other annotation, and I want that the value of @MiTag1 "be extended" by the value of @MiTag2

With my code example, @MiTag2("bla") have to be the same as @MiTag1("bla"), but without hardcode "bla" inside @MiTag2.

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MiTag1 {

    /**
     * The resource key.
     *
     * @see Resources
     */
    String value();
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MiTag1(value = THIS.VALUE)
public @interface MiTag2 {

    /**
     * The resource key.
     *
     * @see Resources
     */
    String value();
}
albertinizao
  • 75
  • 2
  • 5

1 Answers1

0

Java does not permit you to extend from another annotation. This is by design, as it would introduce a fairly complex type system. This question has been answer in detail here, but the important parts are:

Why don’t you support annotation subtyping (where one annotation type extends another)?

It complicates the annotation type system, and makes it much more difficult to write “Specific Tools”.

“Specific Tools” — Programs that query known annotation types of arbitrary external programs. Stub generators, for example, fall into this category. These programs will read annotated classes without loading them into the virtual machine, but will load annotation interfaces.

(original answer from pedromarce)

To bypass this problem, you can either annotate your target type with both annotations @MiTag1 @MiTag2 and set the default value of the should inheriting annotation to the value of the parent annotation.

Also, you can use composition over inheritence and add an annotation of type @MiTag2 to @MiTag2.

Glains
  • 2,773
  • 3
  • 16
  • 30