Annotation in java

Create Annotation

1
2
3
4
5
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {

}
  1. Target and Retention is meta annotation
  2. Target point the annotation’s place in law[SOURCE in default]
  3. Retention point the annotation avaliable time

Create More

1
2
3
4
5
6
7
8
9
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Constraints {

boolean primaryKey() default false;
boolean nullable() default true;
boolean unique() default false;

}
  1. annotation interface’s method will become ture annotation’s property
  2. interface need a default value
  3. type support Primary Type Class String Enum Annotation
1
2
3
4
5
6
7
8
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ConstraintsMore {

Constraints constraints() default
@Constraints(nullable=false);

}

Annotation not support inherit
use default value implements inheritage

1
2
3
4
5
6
7
8
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SqlInteger {

int length() default 0;
Constraints constraints() default @Constraints;

}
1
2
3
4
5
6
7
8
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SqlString {

int length() default 0;
Constraints constraints() default @Constraints;

}

Thinking

Alternative way

  1. Use enumeration type to define the type in DB
    but this way lose agility.

  2. Use String to describe the type you want to define
    but ths way bind handler with DB, if DB changes
    java need to modify and recompile.

  3. Define some annotation more, to describe what you want
    this is good, but maybe a little confusion