Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is @interface used to define annotations?

I have been using annotations in Java or a while as an end user but recently I have decided to look into creating my own annotation types and I find the syntax for defining annotations in Java with @interface to be very strange. My question is why does Java use @interface to define annotations instead of introducing a new keyword like they did for enums? Is there some advantage of the @interface syntax that I am missing?

I am tying to understand the design considerations that the designers of annotations went through I am sure they must have toyed with the idea of introducing a new keyword to define annotations.

@interface has too many restrictions for example you can't use extend, there are specific types you can not use when defining an annotation member such as Date. I find the restrictions on what can go into @interface to be not obvious and it just feels like a hack to me.

like image 709
ams Avatar asked Sep 03 '11 09:09

ams


2 Answers

I don't know the exact considerations for this particular case, but in general:

Introducing a new keyword into a language breaks compatibility of all existing source code that happens to use that particular keyword as an identifier.

The existing source code cannot be compiled with the new compiler version until it's been changed to avoid the keyword. This is not impossible to overcome (as the enum case demonstrated), but it's awkward and forces a lot of people to do extra work. Java's designers have generally tried to introduce new language features without breaking source code compatibility.

In the case of enum, which you mentioned, I guess they decided that it's (a) a common keyword in other C-style languages, (b) generally used only as a local-scope identifier in existing code and thus easily refactored and (c) without any sane alternatives. They decided that the benefits outweighed the costs. For the annotation case, they apparently decided otherwise.

As an aside, you may be interested in watching Josh Bloch's Effective API Design talk which touches on a lot of these considerations.

like image 155
Barend Avatar answered Oct 02 '22 04:10

Barend


Annotation declarations are generally very disgusting to look at.

They probably thought that, only few (experts) will declare and process annotations, most programmers will simply use annotations designed by experts. Therefore they didn't think too much to beautify annotation declarations. enum is supposed to be used by most programmers in their daily job, so the syntax has to be succinct.

But now more and more frameworks like Guice/CDI require/encourage app programmers to declare their own annotations. And many programmers feel brave enough to design and process their own annotations. The problem of messy syntax of annotation declarations becomes more prominent.

like image 21
irreputable Avatar answered Oct 02 '22 02:10

irreputable