Search code examples
javaannotationsmarker-interfaces

Why java annotations?


i want to ask why are the java annotations used so much... I know that they replaced xml configuration in for example jpa, but why is this kind configuration used at all? Consider this piece of code:

@Entity 
class Ent{
   // some fields
}
//... somewhere in the other file far far away
class NonEnt{
   // whatever here
}
Now, when I try to put this in persistence context, with EntityManager's persist method, I get runtime error(better would be to get compile error) with trying to persist NonEnt instance. There is obvious solution for me, force the entities to implement some no-method interface instead of using @Annotations. But this isn't popular among framework designer, what is the drawback of this solution?
Thanks for answering...


Solution

  • When compared to marker interfaces, annotations have some advantages:

    • they can be parameterized
    • they are more fine grained - you can attach them not only to classes but also to other class elements (fields, methods, method arguments, etc)

    Annotations are also supposedly less intrusive, but this point is matter of taste and debatable.

    See also: