概念:
-
内置注解:@Override(覆盖),@Deprecated(定义过期方法),@SuppressWarnings(消除警告)...
-
元注解(用于定义注解):@Target,@Retention...
-
自定义注解:用户自己定义
-
TableName.java
@Target(value={ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TableName {
String value();
}
- TableField.java
@Target(value={ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TableField {
String columnName();
String type();
int length();
}
- StudentEntity.java
@TableName(value="student")
public class StudentEntity {
@TableField(columnName="id",type="int",length=10)
private int id;
@TableField(columnName="name",type="varchar",length=255)
private String name;
@TableField(columnName="age",type="int",length=10)
private int age;
}
- EntityParser.java
public class EntityParser {
public static void main(String[] args) {
try {
Class clazz = Class.forName("com.icngor.annotation.StudentEntity");
TableName tableName= (TableName)clazz.getAnnotation(TableName.class);
System.out.println(tableName.value());
Field field = clazz.getDeclaredField("name");
TableField annotation = field.getAnnotation(TableField.class);
System.out.println(annotation.columnName()+"=="+annotation.type()+"=="+annotation.length());
} catch (Exception e) {
e.printStackTrace();
}
}
}