java Annotation 註解的使用

來源:互聯網
上載者:User

標籤:log   oid   tps   ima   技術分享   代碼   val   hub   測試   

源碼地址:https://github.com/yylxy/JavaAnnotationTest.git

java Annotation 註解的使用 ,代碼中有詳細的注釋。是用AndroidStudio寫的

 

 

 

 

 

/**
* 說明:註解建立類
* 楊陽; 建立於: 2017-06-02 16:10
*/
@Retention(RetentionPolicy.RUNTIME)//定義注釋的生命週期
@Target({ElementType.METHOD, ElementType.TYPE})//注釋的類型,類型是支援方法與類。
public @interface MyAnnotation {
String color() default "blue";//設定的預設值

String value();

int[] array() default {1, 2, 3,};//返回數群組類型

EnumTest enum1() default EnumTest.NAME1;//返回枚舉

OtherAnnotation otherAnnotation() default @OtherAnnotation("hhhhhHHHH");//返回註解
}

 

/**
* 說明:註解使用類
* 楊陽; 建立於: 2017-06-02 16:13
*/
@MyAnnotation(otherAnnotation = @OtherAnnotation("RRRRRRRR"), color = "red", value = "132",array = {4,5,6,7,8},enum1 = EnumTest.NAME2)
public class AnnotationTest {
@Deprecated
@MyAnnotation("456")
public void getString() {
System.out.println("1111111");
}
}

/**
* 說明:註解的反射使用類
* 楊陽; 建立於: 2017-06-02 16:14
*/
public class MyClass {
public static void main(String[] arg) {
AnnotationTest at = new AnnotationTest();
at.getString();
//判斷註解
if (AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)) {
//得到註解
MyAnnotation myAnnotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);
//輸出註解
System.out.println(myAnnotation.color() + "\t\t" + myAnnotation.value());
System.out.println(myAnnotation.array().length + "\t\t" + myAnnotation.toString());
System.out.println(myAnnotation.enum1().name);
System.out.println(myAnnotation.otherAnnotation().value());
}
}
}

 

/**
* 說明:註解建立類
* 楊陽; 建立於: 2017-06-02 17:08
*/
@Retention(RetentionPolicy.RUNTIME)//定義注釋的生命週期
@Target({ElementType.METHOD, ElementType.TYPE})//注釋的類型,類型是支援方法與類。
public @interface OtherAnnotation {
String value() default "yyyyy";

}

 


/**
* 說明:枚舉測試
* 楊陽; 建立於: 2017-06-02 17:31
*/
public enum EnumTest {
NAME1("aaaaa"),NAME2("bbbbb");

String name;

EnumTest(String name) {
this.name = name;
}
}

 

java Annotation 註解的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.