隨筆 - 0, 文章 - 75, 評論 - 0, 引用 - 0
          數(shù)據(jù)加載中……

          java注解(下)

          為注解增加基本屬性:



          什么是注解的屬性:一個注解就相當(dāng)于一個胸卡,如果胸前貼了胸卡,就是該單位的員工,否則就不是。如果還想?yún)^(qū)分是該公司里哪個部門的員工,這時候可以為胸卡再增加一個屬性來進(jìn)行區(qū)分


          加了屬性的標(biāo)記效果為:@MyAnnotation(department="development")



          定義屬性


          ---------------------------------------------------------


          @Retention(RetentionPolicy.RUNTIME)
          //指定注解生命周期
          @Target({ElementType.METHOD,ElementType.TYPE})
          //指定注解作用的范圍
          public @interface MyAnnotation {
          String color() default
          "bule";
          String value(); //特殊方法,當(dāng)只有一個屬性時,不用寫value =
          int[]
          arrayAttr() default {3,4,5};
          //返回枚舉類型的
          EnumTest.TrafficLamp
          lamp() default
          EnumTest.TrafficLamp.RED;
          //返回Annotation類型
          MetaAnnotation
          annotationAttr() default @MetaAnnotation("abc");
          }


          ---------------------------------------------------------



          應(yīng)用屬性


          ---------------------------------------------------------


          @MyAnnotation(annotationAttr=@MetaAnnotation("bbb")
          ,color="red",value="abc",arrayAttr={1,2,3})
          public class AnnotationTest {


          public static void main(String[] args)
          {
          if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){
          //哪個注解在不在
          MyAnnotation annotation =
          AnnotationTest.class.getAnnotation(MyAnnotation.class);
          System.out.println(annotation.color());
          System.out.println(annotation.value());
          System.out.println(annotation.arrayAttr().length);
          System.out.println(annotation.lamp().nextLamp().name());
          //輸出枚舉元素的名
          System.out.println(annotation.annotationAttr().value());
          }
          }



          ---------------------------------------------------------



          定義屬性可以為:


          8個基本類型,String 、Class類型、枚舉類型、注解類型、還可以是前面這些類型的數(shù)組

          posted on 2012-04-22 15:58 hantai 閱讀(63) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 平安县| 惠州市| 民勤县| 花莲市| 会理县| 连山| 阿拉尔市| 茌平县| 利川市| 泰州市| 醴陵市| 格尔木市| 沅江市| 综艺| 龙游县| 宁陕县| 河曲县| 万年县| 马边| 金湖县| 祁东县| 鞍山市| 莲花县| 驻马店市| 华蓥市| 黄冈市| 祁东县| 拜泉县| 深州市| 伊吾县| 瑞金市| 新源县| 德州市| 甘南县| 丰都县| 永年县| 沙坪坝区| 高平市| 连平县| 黎城县| 文登市|