註解字面意思好像是 註釋,提示和說明的做用,可是這樣對於剛接觸這個概念的人,很難理解究竟註解是用來幹嗎的. 好比 Spring MVC中的@Controller, Mybatis中的 @Column. 其實用大白話來講: 註解最大的做用就是替代設計框架的不少的xml文件,使用JAVA的反射機制來讀取註解上的內容,方便框架的使用者. 下面咱們就來一步一步的使用註解來自定義本身的Mybatis框架.java
首先 註解有幾個重要的元註解,也就是在使用JDK自帶的元註解的基礎上才能自定義本身的註解框架
1.一、@Retention: 定義註解的策略,大白話就是定義註解的範圍函數
@Retention(RetentionPolicy.SOURCE) //註解僅存在於源碼中,在class字節碼文件中不包含 @Retention(RetentionPolicy.CLASS) // 默認的保留策略,註解會在class字節碼文件中存在,但 運行時沒法得到, @Retention(RetentionPolicy.RUNTIME) // 註解會在class字節碼文件中存在,在運行時能夠經過反射 獲取到
1.2 @Target:定義註解的目標,大白話就是註解是 類,接口仍是方法或者參數this
@Target(ElementType.TYPE) //接口、類、枚舉、註解 @Target(ElementType.FIELD) //字段、枚舉的常量 @Target(ElementType.METHOD) //方法 @Target(ElementType.PARAMETER) //方法參數 @Target(ElementType.CONSTRUCTOR) //構造函數 @Target(ElementType.LOCAL_VARIABLE)//局部變量 @Target(ElementType.ANNOTATION_TYPE)//註解 @Target(ElementType.PACKAGE) ///包
2.1. Table的定義設計
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE }) public @interface Table { String name() default ""; }
2.2. Column的定義code
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Column { boolean isKey() default false; String value() default ""; }
2.3. 框架使用者定義的User列表xml
@Table(name = "User") public class User { @Column(value = "id", isKey = true) private int id; @Column(value = "name") private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class Annotation { private static void parseAnnotation(Class clazz) throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, SecurityException, InvocationTargetException { Table table = (Table) clazz.getAnnotation(Table.class); System.out.println("table name: " + table.name()); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { Column column = (Column) field.getAnnotation(Column.class); System.out.println("column name: " + column.value() + " isKey: " + column.isKey()); String fieldName = field.getName(); Class<?> type = field.getType(); System.out.println("field name: " + fieldName + " type: " + type); } } public static void main(String args[]) throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, SecurityException, InvocationTargetException { User user = new User(); user.setId(1112111); user.setName("test"); parseAnnotation(user.getClass()); } }