7

Why is it not possible to extend annotations in Java?

 3 years ago
source link: https://www.codesd.com/item/why-is-it-not-possible-to-extend-annotations-in-java.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Why is it not possible to extend annotations in Java?

advertisements

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?


About the reason why it wasn't designed that way you can find the answer in the JSR 175 Design FAQ, where it says:

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.

So, yes I guess, the reason is it just KISS. Anyway, it seems this issue (along with many others) are being looked into as part of JSR 308, and you can even find an alternative compiler with this functionality already developed by Mathias Ricken.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK