Why is it not possible to extend annotations in Ja

2019-01-01 06:30发布

I don't understand why there is no inheritance in Java annotations, just as Java classes. I think it would be very useful.

For example: I want to know if a given annotation is a validator. With inheritance, I could reflexively navigate through superclasses to know if this annotation extends a ValidatorAnnotation. Otherwise, how can I achieve this?

So, can anyone give me a reason for this design decision?

8条回答
笑指拈花
2楼-- · 2019-01-01 07:33

Extensible annotations would effectively add the burden of specifying and maintaing another type system. And this would be a fairly unique type system, so you could not simply apply an OO type paradigm.

Think through all the issues when you introduce polymorphism and inheritance to an annotation (e.g. what happens when sub-annotation changes meta-annotation specs such as retention?)

And all this added complexity for what use-case?

You want to know if a given annotation belongs to a category?

Try this:

@Target(ElementType.ANNOTATION_TYPE)
public @interface Category {
    String category();
}

@Category(category="validator")
public @interface MyFooBarValidator {

}

As you can see, you can easily group and categorize annotations without undue pain using the provided facilities.

So, KISS is the reason for not introducing a meta-type type system to the Java language.

[p.s. edit]

I used the String simply for demonstration and in view of an open ended meta annotation. For your own given project, you obviously can use an enum of category types and specify multiple categories ("multiple inheritance") to a given annotation. Do note that the values are entirely bogus and for demonstration purposes only:

@Target(ElementType.ANNOTATION_TYPE)
public @interface Category {
    AnnotationCategory[] category();
}
public enum AnnotationCategory {
    GENERAL,
    SEMANTICS,
    VALIDATION,
    ETC
}

@Category(category={AnnotationCategory.GENERAL, AnnotationCategory.SEMANTICS})
public @interface FooBarAnnotation {

}

查看更多
路过你的时光
3楼-- · 2019-01-01 07:33

The designers of Java annotation support made a number of "simplifications" to the detriment of the Java community.

  1. No annotations subtypes makes many complex annotations unnecessarily ugly. One cannot simply have an attribute within an annotations that can hold one of three things. One needs to have three separate attributes, which confuses developers and requires runtime validation to ensure that only one of the three is used.

  2. Only one annotation of a given type per site. This has lead to the completely unnecessary collection annotation pattern. @Validation and @Validations, @Image and @Images, etc.

The second one is being remedied in Java 8, but its too late. Many frameworks have been written based on what was possible in Java 5 and now these API warts are here to stay for a good long time.

查看更多
登录 后发表回答