Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Java annotation?

In my project I use pre-defined annotation @With:

@With(Secure.class) public class Test { //.... 

The source code of @With:

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface With {       Class<?>[] value() default {}; } 

I want to write custom annotation @Secure, which will have the same effect as @With(Secure.class). How to do that?


What if I do like this? Will it work?

@With(Secure.class) @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Secure {  } 
like image 411
bvitaliyg Avatar asked Mar 02 '14 11:03

bvitaliyg


People also ask

Is it possible to extend annotations?

In Java SE 6, annotations cannot subclass one another, and an annotation is not allowed to extend/implement any interfaces.

What is @inherited annotation in Java?

@inherited is a type of meta-annotation used to annotate custom annotations so that the subclass can inherit those custom annotations.

What is @interface annotation in Java?

Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.

What is @target annotation in Java?

If an @Target meta-annotation is present, the compiler will enforce the usage restrictions indicated by ElementType enum constants, in line with JLS 9.7. 4. For example, this @Target meta-annotation indicates that the declared type is itself a meta-annotation type.


2 Answers

As piotrek pointed out, you cannot extend Annotations in the sense of inheritance. Still, you can create Annotations that aggregate others:

@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface SuperAnnotation {     String value(); }  @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface SubAnnotation {     SuperAnnotation superAnnotation();     String subValue(); } 

Usage:

@SubAnnotation(subValue = "...", superAnnotation = @SuperAnnotation(value = "superValue")) class someClass { ... } 
like image 95
Halmackenreuter Avatar answered Sep 19 '22 11:09

Halmackenreuter


From Java language specification, Chapter 9.6 Annotation Types:

No extends clause is permitted. (Annotation types implicitly extend annotation.Annotation.)

So, you can not extend an Annotation. you need to use some other mechanism or create a code that recognize and process your own annotation. Spring allows you to group other Spring's annotation in your own custom annotations. but still, no extending.

like image 22
piotrek Avatar answered Sep 18 '22 11:09

piotrek