在运行时修改类定义的注释字符串参数 [英] Modify a class definition's annotation string parameter at runtime

查看:30
本文介绍了在运行时修改类定义的注释字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个类:

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

它已经编译好了(我无法控制源代码),并且是 jvm 启动时类路径的一部分.我希望能够在运行时将某个值"更改为其他值,以便此后的任何反射都具有我的新值,而不是默认的某个值".

Which is already compiled (I cannot control the source), and is part of the classpath when the jvm starts up. I would like to be able to change "some value" to something else at runtime, such that any reflection thereafter would have my new value instead of the default "some value".

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

Is this possible? If so, how?

推荐答案

这段代码或多或少完成了你的要求——它是一个简单的概念证明:

This code does more or less what you ask for - it is a simple proof of concept:

  • 正确的实现还需要处理declaredAnnotations
  • 如果 Class.java 中注解的实现发生变化,代码将会中断(即它可以在未来的任何时间中断)
  • 我不知道是否有副作用...

输出:

oldAnnotation = 一些值
修改注释 = 另一个值

oldAnnotation = some value
modifiedAnnotation = another value

public static void main(String[] args) throws Exception {
    final Something oldAnnotation = (Something) Foobar.class.getAnnotations()[0];
    System.out.println("oldAnnotation = " + oldAnnotation.someProperty());
    Annotation newAnnotation = new Something() {

        @Override
        public String someProperty() {
            return "another value";
        }

        @Override
        public Class<? extends Annotation> annotationType() {
            return oldAnnotation.annotationType();
        }
    };
    Field field = Class.class.getDeclaredField("annotations");
    field.setAccessible(true);
    Map<Class<? extends Annotation>, Annotation> annotations = (Map<Class<? extends Annotation>, Annotation>) field.get(Foobar.class);
    annotations.put(Something.class, newAnnotation);

    Something modifiedAnnotation = (Something) Foobar.class.getAnnotations()[0];
    System.out.println("modifiedAnnotation = " + modifiedAnnotation.someProperty());
}

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

@Retention(RetentionPolicy.RUNTIME)
@interface Something {

    String someProperty();
}

这篇关于在运行时修改类定义的注释字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆