反射给方法注解设置属性值

package com.lantian.test;

import com.pingyougou.manager.controller.TemplateController;
import com.sun.deploy.util.ArrayUtil;
import org.junit.Test;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.security.RolesAllowed;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Map;

public class TestAnnotation {
    @Test
    public void test1() {
        Class<TemplateController> clazz = TemplateController.class;

        // 获取 "方法"上的注解的值
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method: methods){
            if(method.isAnnotationPresent(RolesAllowed.class)){

                RolesAllowed appleAnnotation = method.getAnnotation(RolesAllowed.class);
                try {
                    setAnnotationValue(appleAnnotation,"value","ADMIN_ROLE");
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                String[] value = appleAnnotation.value();
                for (String s : value) {
                    System.out.println(s);
                }
            }
        }
    }


    public static void setAnnotationValue(Annotation annotation, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
        InvocationHandler handler = Proxy.getInvocationHandler(annotation);
        Field field = handler.getClass().getDeclaredField("memberValues");
        field.setAccessible(true);
        Map memberValues = (Map) field.get(handler);
        String[] valueArr = (String[]) memberValues.get("value");

        String[] StrArr = new String[valueArr.length+1];
        for (int i = 0; i < valueArr.length; i++) {
            StrArr[i] = valueArr[i];
        }
        StrArr[StrArr.length-1] = (String) value;

        memberValues.put("value",StrArr);
    }
}
 
posted @ 2020-10-31 20:39  silence022  阅读(77)  评论(0)    收藏  举报