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...
The use of annotations is a lot less invasive than forcing the client to implement a interface or extend a class.
Citing the java tutorial:
As you can see, annotations are a way of specifying meta-data about your types in java, including interfaces, they are in no way a replacement for them.
What you describe is called a "marker interface" and it's an abuse of the interface concept. I suspect the only reason why you consider it obvious is because of
Serializable
- which only exists because there were no annotations at that time.What are its advantages? Annotations have the huge advantage that they can have parameters, and they are much more fine-grained. Marker interfaces only work at the class level.
Java annotation are really helpful when you want to add some additional information to your class, method or instance variable. There are a lot of libraries which use these annotations heavily. These annotations keep the code simple and readable with the power of making changes to the code at runtime.
For example if you have used lombok library, which creates setter, getter and constructor at compile time and saves you lines of code and time.
When compiler executes the code, lomok searches for all the fields marked with @Setter or @Getter annotation and add setter and getter for that field in the class.
One other example is Junit test runner. How junit differentiates between normal helper method in test class and a test. To differentiate between the two it uses @Test annotation.
This tutorial explains how you can use java annotations to create you own test runner.
When compared to marker interfaces, annotations have some advantages:
Annotations are also supposedly less intrusive, but this point is matter of taste and debatable.
See also: