註解的簡單使用
註解定義:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
public int id();
public String description()default "no description";
}
註解的使用:
public class testZj {
@Test(id = 0,description="test description f")
public void f(){
}
@Test(id = 1,description="test description d")
public void d(){
}
@Test(id = 2)
public void e(){
}
}
利用反射查看註解:
public class testfs {
public static void main(String[] args) {
Class cl = testZj.class;
for(Method m : cl.getDeclaredMethods()){
Test a = m.getAnnotation(Test.class);
if(a != null){
System.out.println(a.id() + " " + a.description());
}
}
}
}
運行結果:
0 test description f
1 test description d
2 no description
元註解(註解的註解)
@Target: 表示註解用到什麼地方 有如下參數
- CONSTRUCTOR: 構造器的聲明
- FIELD : 域聲明(包括enum實例)
- LOCAL_VARIABLE: 局部變量的聲明
- METHOD: 方法的聲明
- PACKAGE: 包聲明
- PARAMETER: 參數聲明
- TYPE: 類 接口(包括註解類型) eum 聲明
@Retention: 在什麼級別保存該註解信息 可選參數:
- SOURCE: 被編譯器丟棄
- CLASS: 在class中可用 會被vm丟棄
- RUNTIME: vm在運行期也保留註解 可通過發射讀取
- @Documented: 註解包含在javadoc中
- @Inherited: 允許子類繼承父類的註解