Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...
like image 892
ryskajakub Avatar asked Nov 26 '10 13:11

ryskajakub


People also ask

Why should we use annotations?

Why Annotate? By annotating a text, you will ensure that you understand what is happening in a text after you've read it. As you annotate, you should note the author's main points, shifts in the message or perspective of the text, key areas of focus, and your own thoughts as you read.

What is meant by annotation in Java?

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and Java packages may be annotated. Like Javadoc tags, Java annotations can be read from source files.

Why annotations are used in spring?

Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.


2 Answers

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:

  • Annotations (official JDK documentation)
  • What is the use of marker interfaces in Java?
like image 94
Neeme Praks Avatar answered Sep 28 '22 02:09

Neeme Praks


The use of annotations is a lot less invasive than forcing the client to implement a interface or extend a class.

like image 40
willcodejavaforfood Avatar answered Sep 28 '22 01:09

willcodejavaforfood