首页 > 编程语言 > 详细

spring注解 动态修改注解的值

时间:2021-07-16 10:52:54      阅读:13      评论:0      收藏:0      [点我收藏+]
package com.kafka.consume;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

interface A {
String func1();
}
class B implements A {

@Override
public String func1() {
return "f1";
}
public String func2(){
return "f2";
}
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Foo {
String value();
}
class Bar {
@Foo("fff")
private String val;

@KafkaListener(groupId = "demo", topics = "demo")
public void listenerDemo(ConsumerRecord<?, ?> record) throws Exception{
System.out.println("--"+record.value());
}
}
public class Main {
public static void main(String ...args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException {
Bar bar = new Bar();
Field field = Bar.class.getDeclaredField("val");
Foo foo = field.getAnnotation(Foo.class);
InvocationHandler h = Proxy.getInvocationHandler(foo);
Field hField = h.getClass().getDeclaredField("memberValues");
hField.setAccessible(true);
Map memberValues = (Map) hField.get(h);
memberValues.put("value", "ddd");
String value = foo.value();
System.out.println(value); // ddd
///////
Bar bar1 = new Bar();
Method[] method = Bar.class.getDeclaredMethods();
KafkaListener listener = method[0].getAnnotation(KafkaListener.class);
InvocationHandler hh = Proxy.getInvocationHandler(listener);
Field hFields = h.getClass().getDeclaredField("memberValues");
hFields.setAccessible(true);
Map memberValuess = (Map) hFields.get(hh);
memberValuess.put("groupId", "mayunzhenGroup");
System.out.println(listener.groupId());
}
}

spring注解 动态修改注解的值

原文:https://www.cnblogs.com/yunger/p/15018650.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!