1、定义一个注解
示例:
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
String value() default "";
String msg() default "";
}
@Target-标记这个注解在什么地方使用
其中有10个枚举值,有两个是jdk1.8后新增的,暂时不知道用法
package java.lang.annotation;
public enum ElementType {
TYPE, /* 类、接口(包括注释类型)或枚举声明 */
FIELD, /* 字段声明(包括枚举常量) */
METHOD, /* 方法声明 */
PARAMETER, /* 参数声明 */
CONSTRUCTOR, /* 构造方法声明 */
LOCAL_VARIABLE, /* 局部变量声明 */
ANNOTATION_TYPE, /* 注释类型声明 */
PACKAGE /* 包声明 */
TYPE_PARAMETER /* 1.8之后新增 */
TYPE_USE /* 1.8之后新增 */
}
@Retention-标记这个注解在什么时间使用
其中有3个枚举值
package java.lang.annotation;
public enum RetentionPolicy {
SOURCE, /* Annotation信息仅存在于编译器处理期间,编译器处理完之后就没有该Annotation信息了 */
CLASS, /* 编译器将Annotation存储于类对应的.class文件中。默认行为 */
RUNTIME /* 编译器将Annotation存储于class文件中,并且可由JVM读入 */
}
2、通过类的反射获取到注解以及注解的值
demo示例:
package com.zy.demo;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@TestAnnotation(msg = "类上的注解msg")
public class Test {
@TestAnnotation("value")
private String msgClass;
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
//获取类上的注解
TestAnnotation annotation = Test.class.getAnnotation(TestAnnotation.class);
if (annotation != null) {
System.out.println("value的值为" + annotation.value());
System.out.println("msg的值为" + annotation.msg());
}
//获取方法上的注解
Method method = Test.class.getMethod("testMsg");
TestAnnotation annotation1 = method.getAnnotation(TestAnnotation.class);
if (annotation1 != null) {
System.out.println("-----------------");
System.out.println("value的值为" + annotation1.value());
System.out.println("msg的值为" + annotation1.msg());
}
//获取属性上的注解
Field a = Test.class.getDeclaredField("msgClass");
TestAnnotation annotation2 = a.getAnnotation(TestAnnotation.class);
if (annotation1 != null) {
System.out.println("-----------------");
System.out.println("value的值为" + annotation2.value());
System.out.println("msg的值为" + annotation2.msg());
}
}
@TestAnnotation(value = "方法上的注解value" ,msg = "方法上的注解msg")
public void testMsg() {
}
}
执行结果为: