1.自定义注解
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Mytag {
String name() default "";
}
2.扩展注解的实现类
public class MyTagImpl implements Mytag{
private String name;
public MyTagImpl(String name) {
this.name = name;
}
@Override
public String name() {
return name;
}
@Override
public Class<? extends Annotation> annotationType() {
return MyTagImpl.class;
}
}
3.util
public class AnnotationUtil {
public static void alterAnnotationOn(Class clazzToLookFor, Class<? extends Annotation> annotationToAlter, Annotation annotationValue) {
try {
//jdk中标记的元信息分为annotations和AnnotationData annotations这个容器是AnnotationData对象的属性
Method method = Class.class.getDeclaredMethod("annotationData", null);
method.setAccessible(true);
//通过反射的方法调用创建对象
Object annotationData = method.invoke(clazzToLookFor);
//反射获取对象属性
Field annotations = annotationData.getClass().getDeclaredField("annotations");
annotations.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData);
map.put(annotationToAlter, annotationValue);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.测试
@Mytag(name = "111")
public class Test {
public static void main(String[] args) {
Mytag mytag = Test.class.getAnnotation(Mytag.class);
System.out.println("--修改之前:----" + mytag.name());
MyTagImpl altered = new MyTagImpl("hello dxy");
AnnotationUtil.alterAnnotationOn(Test.class, Mytag.class, altered);
mytag = Test.class.getAnnotation(Mytag.class);
System.out.println("--修改之后:----" + mytag.name());
}
}
5.结果