注解學習筆記之自定義注解
@Target({1,2,3,4,5,6,7})
- 1.ElementType.CONSTRUCTOR:用于描述構造器
- 2.ElementType.FIELD:用于描述域
- 3.ElementType.LOCAL_VARIABLE:用于描述局部變量
- 4.ElementType.METHOD:用于描述方法
- 5.ElementType.PACKAGE:用于描述包
- 6.ElementType.PARAMETER:用于描述參數
- 7.ElementType.TYPE:用于描述類、接口(包括注解類型) 或enum聲明
@Retention(1/2/3)
- 1.RetentionPolicy.SOURCE:注解只保留在源文件,當Java文件編譯成class文件的時候,注解被遺棄;
- 2.RetentionPolicy.CLASS:注解被保留到class文件,但jvm加載class文件時候被遺棄,這是默認的生命周期;
- 3.RetentionPolicy.RUNTIME:注解不僅被保存到class文件中,jvm加載class文件之后,仍然存在;
自定義注解的練習代碼
SxtTable
- 類和表的對應注解
/*** 自定義一個類和表的對應注解*/import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.TYPE)//指明此注解用于注解類
@Retention(RetentionPolicy.RUNTIME)//指明注解不僅被保存到class文件中,jvm加載class文件之后,仍然存在
public @interface SxtTable {String value();//值為類對應的表名
}
SxtField
- 屬性注解
/*** 自定義一個屬性注解*/import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SxtField {String columnName();//表中字段的列名String type();//字段的類型int length();//字段的長度
}
SxtStudent
- 學生類
/*** 創建一個student類并使用自定義的注解*/
@SxtTable("tb_student")//對類使用注解
public class SxtStudent {@SxtField(columnName = "id",type ="int",length = 10)//對屬性id使用注解private int id;@SxtField(columnName = "sname",type ="varchar",length = 10)//對屬性studentName使用注解private String studentName;@SxtField(columnName = "age",type ="int",length = 4)//對屬性age使用注解private int age;public int getId() {return id;}public void setId(int id) {this.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;}
}
SxtTest
- 測試類獲取注解信息并打印
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;/*** 使用反射讀取注解信息,模擬注解信息處理的流程*/
public class SxtTest {public static void main(String[] args) {try {Class clazz = Class.forName("com.sxt.SxtStudent");//獲得類所有的注解(這只直接獲得所有有效的注解)Annotation[] annotations = clazz.getAnnotations();for (Annotation annotation : annotations) {//打印獲取到的注解信息System.out.println(annotation);}//也可以獲得指定的注解(獲得指定的注解)這里指定的是SxtTable 如果有多個類注解也可以依次指定SxtTable sxtTable = (SxtTable) clazz.getAnnotation(SxtTable.class);//打印獲取到的注解信息System.out.println(sxtTable.value());//獲得屬性的注解(這里只拿studentName這一個屬性來做示例)Field studentName = clazz.getDeclaredField("studentName");SxtField sxtField = studentName.getAnnotation(SxtField.class);//打印獲取到的注解信息System.out.println(sxtField.columnName()+"--"+sxtField.type()+"--"+sxtField.length());//根據獲得的表名,字段信息,可以通過jdbc 執行sql語句在數據庫中生成對應的表//本例用來練習自定義注解故不再往下往下寫只對信息進行了打印} catch (Exception e) {e.printStackTrace();}}
}