ZBLOG

public class MyClass { @MyAnnotation(value = "example") private String myField; // 其他成员和方法定义 }通过反射给@MyAnnotation中的value赋值

通过反射给注解中的属性赋值可以按照以下步骤进行:

  1. 获取 MyClass 类的 myField 属性的 Field 对象:
Field field = MyClass.class.getDeclaredField("myField");
  1. 获取 @MyAnnotation 注解对象:
MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
  1. 使用 Java 反射 API 设置注解属性值:
Method valueMethod = MyAnnotation.class.getDeclaredMethod("value");
valueMethod.setAccessible(true); // 设置为可访问
valueMethod.invoke(annotation, "new value"); // 传入新的值

完整代码示例如下:

import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyClass {
    @MyAnnotation(value = "example")
    private String myField;

    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Field field = MyClass.class.getDeclaredField("myField");
        MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);

        Method valueMethod = MyAnnotation.class.getDeclaredMethod("value");
        valueMethod.setAccessible(true);
        valueMethod.invoke(annotation, "new value");

        System.out.println(annotation.value()); // 输出:new value
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MyAnnotation {
    String value() default "";
}

这样,我们就通过反射成功修改了注解中的属性值。需要注意的是,这种方式只能在运行时修改注解属性值,并且需要确保被修改的注解属性有相应的 setter 方法。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=10894

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?