java Annotation 注解的使用

源码地址: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;
}
}

 

posted @ 2017-07-12 11:38  宇悟行  阅读(284)  评论(0编辑  收藏  举报