What is the function of these Java annotations?

I still don't understand the purpose of annotation in Java. Initially, I thought they simply served as documentation. But looking at this documentation from the Google App Engine Datastore , I'm not sure. @PersistenceCapable (identityType = IdentityType.APPLICATION) is more like a method signature.

What is the purpose of this type of annotation? What is he doing?

import java.util.Date; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; @PersistenceCapable(identityType = IdentityType.APPLICATION) public class Employee { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private String firstName; @Persistent private String lastName; @Persistent private Date hireDate; public Employee(String firstName, String lastName, Date hireDate) { this.firstName = firstName; this.lastName = lastName; this.hireDate = hireDate; } // Accessors for the fields. JDO doesn't use these, but your application does. public Long getId() { return id; } public String getFirstName() { return firstName; } // ... other accessors... } 
+7
java annotations
source share
3 answers

This is source level metadata. This is a way of adding information to code that is not code and that is easily processed by the machine.

In your example, they are used to set up object-relational mapping for this type of entity. He says that, for example, the id field should be the primary key for this object, and that firstName, lastName and hireDate should be stored in the database. (To specify these fields except the state of the transition object.)

GAE support for JDO needs to know which objects you are trying to store in the database. It does this by looking at classes in your code, looking for those that are annotated with @PersistenceCapable.

They are usually used to replace where you used external configuration files; the standard Java library has tools for reading annotations in your code, which greatly simplifies their processing than deploying your own configuration file, and you get free IDE support.

+9
source share

Annotations can be processed using annotation processing APIs to automatically create a code template.

+1
source share

I think they are taken from the Java Data Objects API. This is an API that partially matches what EJB3 should do. The same concepts, different syntax and tools.

If you are not familiar with annotations at all, check out the Java tutorial.

0
source share

All Articles