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

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

问题描述

想象一下有一个类:

@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 =某个值

modifiedAnnotation =另一个值

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天全站免登陆