Sunday, January 24, 2016

Full Example of declare and use an annotation

To see the basic concept of Annotation: here
To see the basic concept of declare an Annotation: here

Declare table and field annotation for SQL database, so when we can build ORM(Object Relationship Mapping)

SQLTable Annotation:
public @interface SQLTable {
 String value(); //table name

SQLField Annotation:
public @interface SQLField {
 String column();
 String type();
 int length();
Table structure

A Model class using annotations as description
public class Student {
 private int id;
 private String studentName;
 private int age;
 public int getId() {
  return id;
 public void setId(int id) { = id;
 public String getStudentName() {
  return studentName;
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 public int getAge() {
  return age;
 public void setAge(int age) {
  this.age = age;

Use Annotation to build SQL:

public class Demo2 {
 public void test(){
   Class clazz = Class.forName("model.Student");
   //(1)get all annotations for the class
   Annotation[] annotations = clazz.getAnnotations();
   for(Annotation a: annotations){
   //(1) get the specified annotation for the class
   SQLTable table = (SQLTable) clazz.getAnnotation(SQLTable.class);
   //(2) get annotation for the field
   Field f = clazz.getDeclaredField("studentName"); //get the target field from class
   SQLField myField = f.getAnnotation(SQLField.class); //get the annotation for this field
   //use function declared in annotation
   //based on (1) and (2), we can build up all info for the related sql table   
  }catch(Exception e){

No comments:

Post a Comment