对反射有一定了解过后学习注解就会轻松许多,这篇文章会创建创建字段,方法,参数上面的注解,并且通过反射的形式将注解内容拿出来。
下面是自定义注解的简短讲解
1,自定义注解,创建一个只能修饰方法的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AnnotationMethod {String value();
}
注解的写法如下,别问我为什么这么写,规定的
用@interface注解的接口
public @interface AnnotationMethod {String value();
}
自定义注解必须有这两个参数
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
@Retention 注解的生命周期,这里一般用RUNTIME:表示在运行时
@Target注解可以修饰的范围:METHOD表示方法,只有METHOD修饰的只能用在方法上,
接下来多创建几个不同的注解
2,创建一个只能修饰字段的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AnnotationField {String value();
}
3,创建一个只能修饰方法参数的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface AnnotationParameter {String value();
}
4,使用注解
public class AnnotationUser {@AnnotationField("field")public String name;@AnnotationMethod("method")public void setName(@AnnotationParameter("Parameter") String name) {}
}
5,通过代码获取到类class上的所有注解
public void start() {//反射获取类有多少个字段Field[] fields = AnnotationUser.class.getFields();for (int i = 0; i < fields.length; i++) {Field field = fields[i];//通过字段的getAnnotations()获取到该字段有多少个注解for (Annotation annotation : field.getAnnotations()) {//判断字段的注解是不是我们自定义的注解if (annotation instanceof AnnotationField) {AnnotationField annotationField = (AnnotationField) annotation;//打印字段的名字Log.e("AnnotationTest", "field name: " + field);//打印字段的注解Log.e("AnnotationTest", "field annotation: " + annotationField.value());}}}//反射获取类有多少个方法Method[] methods = AnnotationUser.class.getMethods();for (Method method : methods) {//获取每个方法中有多少个注解for (Annotation annotation : method.getAnnotations()) {//判断方法的注解是不是我们自定义的注解if (annotation instanceof AnnotationMethod) {AnnotationMethod data = (AnnotationMethod) annotation;//打印方法名称Log.e("AnnotationTest", "method Name: " + method.getName());//打印注解Log.e("AnnotationTest", "method annotation: " + data.value());}}//获取每个方法有到少个参数for (Parameter parameter : method.getParameters()) {//获取每个字段上面所有注解for (Annotation annotation : parameter.getAnnotations()) {//判断参数的注解是不是我们自定义的注解if (annotation instanceof AnnotationParameter) {AnnotationParameter data = (AnnotationParameter) annotation;//打印参数名称Log.e("AnnotationTest", "Parameter Name: " + parameter.getName());//打印注解Log.e("AnnotationTest", "Parameter annotation: " + data.value());}}}}}
6,这样就可以获取到上面的一个class文件上所有的注解了,打印如下
