java反射修改類註解屬性
阿新 • • 發佈:2021-02-14
View Code@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) { }