在运行时修改类定义的注释字符串参数

2023-12-07

想象一下有一个类:

@Something(someProperty = "some value")
public class Foobar {
    //...
}

它已经编译(我无法控制源代码),并且是 jvm 启动时类路径的一部分。我希望能够在运行时将“某些值”更改为其他值,这样此后的任何反射都会有我的新价值而不是默认的“某个值”。

这可能吗?如果是这样,怎么办?


Warning: Not tested on OSX - see comment from @Marcel

在 OSX 上测试。工作正常。

由于我还需要在运行时更改注释值,因此我重新审视了这个问题。

这是 @assylias 方法的修改版本(非常感谢您的启发)。

/**
 * Changes the annotation value for the given key of the given annotation to newValue and returns
 * the previous value.
 */
@SuppressWarnings("unchecked")
public static Object changeAnnotationValue(Annotation annotation, String key, Object newValue){
    Object handler = Proxy.getInvocationHandler(annotation);
    Field f;
    try {
        f = handler.getClass().getDeclaredField("memberValues");
    } catch (NoSuchFieldException | SecurityException e) {
        throw new IllegalStateException(e);
    }
    f.setAccessible(true);
    Map<String, Object> memberValues;
    try {
        memberValues = (Map<String, Object>) f.get(handler);
    } catch (IllegalArgumentException | IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
    Object oldValue = memberValues.get(key);
    if (oldValue == null || oldValue.getClass() != newValue.getClass()) {
        throw new IllegalArgumentException();
    }
    memberValues.put(key,newValue);
    return oldValue;
}

使用示例:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ClassAnnotation {
  String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldAnnotation {
  String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodAnnotation {
  String value() default "";
}
@ClassAnnotation("class test")
public static class TestClass{
    @FieldAnnotation("field test")
    public Object field;
    @MethodAnnotation("method test")
    public void method(){

    }
}

public static void main(String[] args) throws Exception {
    final ClassAnnotation classAnnotation = TestClass.class.getAnnotation(ClassAnnotation.class);
    System.out.println("old ClassAnnotation = " + classAnnotation.value());
    changeAnnotationValue(classAnnotation, "value", "another class annotation value");
    System.out.println("modified ClassAnnotation = " + classAnnotation.value());

    Field field = TestClass.class.getField("field");
    final FieldAnnotation fieldAnnotation = field.getAnnotation(FieldAnnotation.class);
    System.out.println("old FieldAnnotation = " + fieldAnnotation.value());
    changeAnnotationValue(fieldAnnotation, "value", "another field annotation value");
    System.out.println("modified FieldAnnotation = " + fieldAnnotation.value());

    Method method = TestClass.class.getMethod("method");
    final MethodAnnotation methodAnnotation = method.getAnnotation(MethodAnnotation.class);
    System.out.println("old MethodAnnotation = " + methodAnnotation.value());
    changeAnnotationValue(methodAnnotation, "value", "another method annotation value");
    System.out.println("modified MethodAnnotation = " + methodAnnotation.value());
}

这种方法的优点是,不需要创建新的注释实例。因此不需要提前知道具体的注解类。此外,副作用应该是最小的,因为原始注释实例保持不变。

使用 Java 8 进行测试。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在运行时修改类定义的注释字符串参数 的相关文章

随机推荐

  • Android - WebView 不播放 YouTube 视频

    我有一些 WebView 代码 我试图用它在 YouTube 频道上播放 YouTube 视频 但它所做的只是在视频上显示旋转图标 而从未真正启动视频 有人知道如何解决这个问题吗 public class YoutubeActivity e
  • PHP 回发 url 谷歌钱包 IAP

    我的谷歌钱包应用内支付的回发 php 如下所示
  • 使用数组参数调用本机函数

    我完全不知道如何使用数组参数调用本机 dll 中的函数 Example 该函数在 C 项目中定义为 DllImport Project2 dll SetLastError true CallingConvention CallingConv
  • 如何将对象注入 Ninject 模块

    我正在使用 Ninject 进行 DI 我有 Ninject 模块 它将一些服务绑定到内核 并使用其他模块中的绑定对象作为服务 为了弄清楚这种情况 让我们看几行代码 这是我的安全模块 它提供了一个名为PermissionManagerCon
  • 使用 NHibernate QueryOver 实现“不存在的地方”

    使用新的QueryOverNHibernate 中的 API 我需要做一些相当于 select c from Category c where not exists select from CategoryProduct cp where
  • 在 VS2010 中将 version=10.0.0.0 替换为 11.0.0.0 进行更改后出现新的构建错误

    我遇到了同样的问题构建错误 创建 Excel 2010 的 VSTO 插件 根据解决方案进行更改后 我得到了新的错误 The InitializeDefaultProperties task could not be loaded from
  • XmlSerializer 保存临时文件的最安全位置

    我注意到 XmlSerializer 需要使用磁盘空间来执行其命令 如果没有可写的 temp 文件夹 则会失败并出现如下错误 Source System Xml Message Unable to generate a temporary
  • Task.Run(async () => wait MethodAsync()).Result 和 MethodAsync().Result 之间有什么区别吗? [关闭]

    Closed 这个问题需要多问focused 目前不接受答案 我需要实现一个不支持异步的第三方接口 特别是来自 automapper 的 IValueResolver 我想知道这两段代码有什么区别 使用第一个而不是第二个有什么优点吗 我将在
  • 在 Spring Boot 中每个数据库连接开始时运行 SQL 语句

    如何使用Spring Boot获得数据库连接后直接运行自定义SQL语句 每次建立新连接时都需要运行 SQL 该解决方案应该与 Spring Boot 默认 DataSource 实现 我认为是 Tomcat 池数据源 一起使用 声明是什么并
  • 什么是互递归类型?

    如果在 ML 中 递归数据类型的示例是 datatype llist Nil Node of int llist 什么是机器学习中的相互递归数据类型以及它的示例是什么 这些愚蠢的数据类型就是这样的一个例子 datatype a A Ab o
  • FirebaseInstanceId:传递消息时出错:MI 设备中未找到 ServiceIntent

    当应用程序长时间处于后台时 我们发现了此错误 我在小米设备中发现了这个问题 我在三星进行了测试 它运行完美 但在小米中 它总是抛出相同的错误 None
  • findOne 可以先匹配还是最后匹配?

    我专门使用猫鼬 尽管我不认为这有那么重要 例如 假设我有一个名为 MongoQueue 的集合 并且我向该队列添加了一些人 MongoQueue save function err firstPerson if err console lo
  • 使用不同的因变量重复回归

    我已经在 Stack 和 google 上搜索了解决方案 但没有找到解决我的问题的方法 我有大约 40 个因变量 我的目标是获得调整后的均值 lsmeans 在考虑了一些协变量后 我需要调整 A 组和 B 组的均值 我的最终对象应该是一个数
  • 在 matplotlib 中使用更多颜色进行绘图

    我正在尝试使用 matplotlib 绘制散点图 但收到 IndexError 从空列表中弹出 错误 我不知道如何修复它 import matplotlib pyplot as plt import matplotlib import nu
  • 表格单元格在行内右对齐

    我试图弄清楚如何将单元格移动到 HTML 表格的左侧 我想在最后一行使用更少的单元格 默认情况下它位于右侧 例如我有这张表 table tr th one th th two th th three th tr tr td one td t
  • Android v2 MapFragment 在 Scrollview 中滚动时抖动

    我正在使用 SupportMapFragment 在 ScrollView 中显示静态地图 我不喜欢移动 缩放地图 只显示位置 当我向下 向上滚动时 地图在其边界内晃动 感觉非常滞后 我的问题是 如何消除这种滞后 或者如何使用 v2 api
  • 在 Java 中 Ping 多个服务器 [重复]

    这个问题在这里已经有答案了 我有一个程序可以向服务器发送 ping 请求 该列表很大 如果IP无法到达 需要时间才能转到下一个IP 我希望 对于每一个IP 它应该创建一个新线程并同时处理所有线程 这是代码 for int i 0 i lt
  • Jackson @JsonProperty(required=true) 不会抛出异常

    我正在使用 jackson 2 2 注释 JsonProperty 并将 required 设置为 true 通过 ObjectMapper readValue 方法反序列化不包含该属性的 json 文件时 不会引发异常 它应该以不同的方式
  • 在 SQL Server 中执行列值[重复]

    这个问题在这里已经有答案了 我需要对 SQL 表中保存的值进行算术运算 例如 我在下一列中的值为 5 10 我想要 15 EQUATION VALUE 2 5 7 6 8 14 根据方程式我需要计算该值 正如您现在所知 SQL Server
  • 在运行时修改类定义的注释字符串参数

    想象一下有一个类 Something someProperty some value public class Foobar 它已经编译 我无法控制源代码 并且是 jvm 启动时类路径的一部分 我希望能够在运行时将 某些值 更改为其他值 这