java反射修改类注解属性

@Component(value = "student")
public class Student {

    static {
        Class st = com.example.demo12.classs.Student.class;
        Component component = (Component) st.getAnnotation(Component.class);
        System.out.println("开始===========" + component.value());
        //获取 foo 这个代理实例所持有的 InvocationHandler
        InvocationHandler h = Proxy.getInvocationHandler(component);
        Map memberValues = null;
        try {
            // 获取 AnnotationInvocationHandler 的 memberValues 字段
            Field hField = h.getClass().getDeclaredField("memberValues");
            // 因为这个字段事 private final 修饰,所以要打开权限
            hField.setAccessible(true);
            // 获取 memberValues
            memberValues = (Map) hField.get(h);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        // 修改 value 属性值
        memberValues.put("value", "teacher");
        // 获取 foo 的 value 属性值
        String value = component.value();
        System.out.println("结束===========" + value);
    }

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    /**
     * 
     * @param args
     */
    public static void main(String[] args) {

    }
View Code

 

posted @ 2020-11-13 14:30  土木转行的人才  阅读(482)  评论(0编辑  收藏  举报