標籤: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 註解的使用