Java反射解析自定义注解
自定义注解
1.自定义注解需要使用@interface关键字。自定义注解自动继承了java.lang.annotation.Annotation接口。
注解定义配置参数不设置默认值
注解定义配置参数并设置默认值
通过default关键字来声明配置参数的默认值。
使用反射技术解析自定义注解
目前流行框架都是:注解+反射+设计模式。所以自定义完注解后,需要使用反射技术来解析。
如果只是单纯定义注解,不做任何处理,将毫无意义。
自定义注解代码
package cn.xxxq.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
/*
这个方法相当于定义了一个配置参数:
1.参数名称是方法名。
2.参数类型是方法返回值类型。
类型只能是八种基本类型、String类型、Class类型、enum类型、Annotation类型
*/
String[] name();
/*不能是包装类型*/
// Integer[] height();
char sex();
// String[] value() default "javaee"; //也可以只给一个值
String[] value() default {"java","javaee"};
int age() default 21;
}
解析注解代码
package cn.xxxq.annotation;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.stream.Stream;
/*
name和sex参数没有默认值所以必须赋值
value和age参数有默认值了,可以不赋值
*/
@MyAnnotation(name = "zwq",sex = '男')
public class MyAnnotationTest {
public static void main(String[] args) {
String className = "cn.xxxq.annotation.MyAnnotationTest";
printMsgForAnnotation(className);
}
/**
* 输出一个类上所有注解的信息
* @param className 类的全限定名称
*/
public static void printMsgForAnnotation(String className){
try {
/*获取指定类的字节码对象*/
Class<?> clazz = Class.forName(className);
//获得类上所有的注解
Annotation[] annotations = clazz.getAnnotations();
/*Stream流打印所有注解*/
Stream.of(annotations).forEach(System.out::println);
/*获得类上指定的注解*/
MyAnnotation annotation = clazz.getAnnotation(MyAnnotation.class);
/*打印该注解value参数的值*/
System.out.println(Arrays.asList(annotation.value()));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
解析结果
@cn.xxxq.annotation.MyAnnotation(value=[java, javaee], age=21, name=[zwq], sex=男)
[java, javaee]