Change annotation value of field annotation in Java 8

﹥>﹥吖頭↗ 提交于 2020-01-01 14:37:56

问题


I think title describes the problem. Here's some code:

import static org.junit.Assert.assertEquals;
import java.lang.annotation.*;

public class Main {
    public static void main(String[] args) throws Exception {
        assertEquals("foo", Main.class.getDeclaredMethod("myMethod").getAnnotation(Anno.class).param());

        // the magic here -> set to bar

        assertEquals("bar", Main.class.getDeclaredMethod("myMethod").getAnnotation(Anno.class).param());
    }

    @Anno(param = "foo")
    public void myMethod() {}

    @Retention(RetentionPolicy.RUNTIME)
    @interface Anno {
        String param();
    }
}

So far I'm guessing this is not possible. It seems that always when you try to get a method via reflection you only get copies and all values (like annotations) are reread from a deeper java layer. In these copies you could change values but these are gone if you reload.

Is there something I missed or is it really not possible?


回答1:


Annotations are modifiers just like private or synchronized. They are part of the invariant static structure of a class and not intended to be modified. You can hack into the Reflection implementation to make a particular method print what you want, but besides the dirtiness of the hack, you simply haven’t changed the annotation, you just hacked a data structure of a particular library.

There are other Reflection or byte code manipulation libraries which won’t use the built-in Reflection API but read the byte code directly (e.g. via getResource() or via the Instrumentation API). These libraries will never notice your manipulation.

Note further, since these values are supposed to be constants embedded in the class file, a Reflection implementation could always use lazy fetching plus dropping of the cached values depending on uncontrollable conditions as these values can always be refetched. There’s also no guaranty that the Reflection implementation uses data structures at all; it could also generate code returning the constant values.

In other words, if you want to associate mutable data with a method, don’t use annotations. You could simple use a Map<Method,MutableData>, or, if you just have that one particular method, declare a good old static field which already provides all the features you need and is much easier to handle.




回答2:


I posted a link to do the same task before Java 8. It seems to be possible to do the same in Java 8 (1.8.0_51). The whole test setup

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

public class Test {
    public static void main(String... args) {
        Test t = new Test();
        t.check();
        Test.change();
        t.check();
        new Test().check();
    }

    public Test() {

    }

    public static void change() {
        try {
            Method m = Test.class.getMethod("myMethod");
            // The map has to be built for the first time
            m.getDeclaredAnnotations();
            Class<?> superclass = m.getClass().getSuperclass();
            Field declaredField = superclass.getDeclaredField("declaredAnnotations");
            declaredField.setAccessible(true);
            @SuppressWarnings("unchecked")
            Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) declaredField
                    .get(m);
            map.put(Anno.class, new Anno() {

                @Override
                public Class<? extends Annotation> annotationType() {
                    return Anno.class;
                }

                @Override
                public String param() {
                    return "new";
                }
            });
        } catch (SecurityException | NoSuchMethodException | IllegalArgumentException | NoSuchFieldException
                | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public void check() {
        try {
            System.out.println(getClass().getMethod("myMethod").getAnnotation(Anno.class).param());
        } catch (NoSuchMethodException | SecurityException e) {
            e.printStackTrace();
        }
    }

    @Anno(param = "test")
    public void myMethod() {
    }

}

@Retention(RetentionPolicy.RUNTIME)
@interface Anno {
    String param();
}


来源:https://stackoverflow.com/questions/32089290/change-annotation-value-of-field-annotation-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!