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
TYPE_USE
}
@Retention-标记这个注解在什么时间使用
其中有3个枚举值
package java.lang.annotation;
public enum RetentionPolicy {
SOURCE,
CLASS,
RUNTIME
}
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() {
}
}
执行结果为:



