有的场景需要动态修改注解中的属性值。
定义注解
@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldInfo {
int order();
int size() default -1;
}
动态修改data字段上FieldInfo注解中的size属性值。利用Java的“反射”实现在程序中根据业务进行动态的修改。
Field sample = UploadImageRequest.class.getDeclaredField("data");
MagicField annotation = sample.getAnnotation(FieldInfo.class);
InvocationHandler handler = Proxy.getInvocationHandler(annotation);
Field field = handler.getClass().getDeclaredField("memberValues");
field.setAccessible(true);
Map map = (Map) field.get(handler);
//报文长度
int packetLength = in.getUnsignedShortLE(2);
map.put("size",10);
这样size属性值就修改了。