javydreamercsw javydreamercsw - 1 month ago 15
Java Question

Is there something like Annotation Inheritance in java?

I'm exploring annotations and came to a point where some annotations seems to have a hierarchy among them.

I'm using annotations to generate code in the background for Cards. There are different Card types (thus different code and annotations) but there are certain elements that are common among them like a name.

@Target(value = {ElementType.TYPE})
public @interface Move extends Page{
String method1();
String method2();
}


And this would be the common Annotation:

@Target(value = {ElementType.TYPE})
public @interface Page{
String method3();
}


In the example above I would expect Move to inherit method3 but I get a warning saying that extends is not valid with annotations. I was trying to have an Annotation extends a common base one but that doesn't work. Is that even possible or is just a design issue?

Answer

Unfortunately, no. Apparently it has something to do with programs that read the annotations on a class without loading them all the way. See Why is not possible to extend annotations in Java?

However, types do inherit the annotations of their superclass if those annotations are @Inherited.

Also, unless you need those methods to interact, you could just stack the annotations on your class:

@Move
@Page
public class myAwesomeClass {}

Is there some reason that wouldn't work for you?