Java自定义注解并通过反射读取
Java自定义注解并通过反射读取
- 自定义注解
- 元注解
- @Target
- @Retention
- 使用反射机制读取注解信息
自定义注解
- 使用@interface自定义注解,自动继承了java.lang.annotation接口
格式为:
- public @interface 注解名 {定义体}
- 其中的每个方法实际上是声明了一个配置参数
- 方法的名称就是参数的名称
- 返回值的参数就是参数的类型(返回值类型只能是基本类型、Class、String、enum)
- 可以通过default来声明参数的默认值。
- 如果只有一个参数成员,一般参数名为value
- 注意:注解元素必须要有值。我们定义注解元素时,经常使用空字符串、0作为默认值。 也经常使用负数(比如:-1)表示不存在的含义
元注解
- 元注解的作用就是负责注解其他注解。Java定义了4个标准的meta-annotation类型,他们被用来提供对其他annotation类型作说明。
这些类型和它们所支持的类在java.lang.annotation包中可以 找到
- @Target
- @Retention
- @Documented
- @Inherited
@Target
- 作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
所修饰范围 | 取值ElementType |
---|---|
package 包 | PACKAGE |
类、接口、枚举、Annotation类型 | TYPE |
类型成员(方法、构造方法、成员变量、枚举值) | CONSTRUCTOR:用于描述构造器 FIELD:用于描述域 METHOD:用于描述方法 |
方法参数和本地变量 | LOCAL_VARIABLE:用于描述局部变量 PARAMETER:用于描述参数 |
- 例如:@Target(value=ElementType.TYPE)
@Retention
- 作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期
取值RetentionPolicy | 作用 |
---|---|
SOURCE | 在源文件中有效(即源文件保留) |
CLASS | 在class文件中有效(即class保留) |
RUNTIME | 在运行时有效(即运行时保留) 为Runtieme可以被反射机制读取 |
使用反射机制读取注解信息
try {
Class clazz = Class.forName("com.wj.test.annotation.WjtStudent");
//获得类的所有有效注解
Annotation[] annotations=clazz.getAnnotations();
for (Annotation a : annotations) {
System.out.println(a);
}
//获得类的指定的注解
WjTable wt = (WjTable) clazz.getAnnotation(WjTable.class);
System.out.println(wt.value());
//获得类的属性的注解
Field f = clazz.getDeclaredField("studentName");
WjField wjField = f.getAnnotation(WjField.class);
System.out.println(wjField.columnName()+"--"+wjField.type()+"--"+wjField.length());
} catch (Exception e) {
e.printStackTrace();
}
还没有评论,来说两句吧...