3

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?

Marcel
  • 4,054
  • 5
  • 36
  • 50
  • Possible duplicate http://stackoverflow.com/questions/14268981/modify-a-class-definitions-annotation-string-parameter-at-runtime – Flown Aug 19 '15 at 07:53
  • 2
    @Flown, an accepted answer in that question does not work in Java-8. It's possible to solve this, but of course the solution would be very dirty and fragile. I guess, it's much better to give up and move to solve the *original* problem instead. – Tagir Valeev Aug 19 '15 at 07:56

2 Answers2

3

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.

Holger
  • 285,553
  • 42
  • 434
  • 765
1

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();
}
Flown
  • 11,480
  • 3
  • 45
  • 62
  • 1
    That's fine, but OPs code contains not `m.getAnnotation(Anno.class)`, but `getClass().getMethod("myMethod").getAnnotation(Anno.class)` which does not work with your answer. The `getClass().getMethod("myMethod")` always returns a fresh copy of internal `Method`, which is located in the array field of soft-referenced private class. So you will need much more reflection and keep the strong-reference somewhere to ensure the soft-ref is not expired. – Tagir Valeev Aug 19 '15 at 08:50
  • Have you tried the code? It seems to work if you append `System.out.println(getClass().getMethod("myMethod").getAnnotation(Anno.class).param());` after the last System.out::println. – Flown Aug 19 '15 at 08:55
  • 1
    I tried on 1.8.0_25. It works in 1.8.0_40, but does not work on 1.8.0_25. – Tagir Valeev Aug 19 '15 at 09:01
  • I tested it on 1.8.0_51 – Flown Aug 19 '15 at 09:41
  • 1
    To sum up this attempt i have to quote your first comment: "It's dirty and fragile". – Flown Aug 19 '15 at 09:49
  • 2
    I wouldn’t call this a solution given the question’s wording. The question was about changing the annotation, but this hack only changes what certain Reflection code (of a certain implementation) will report. You could achieve the same by manipulating the `PrintStream` to show what you want to see, but I assume that then everyone would agree that this is not a solution. But the principle is the same… – Holger Aug 19 '15 at 10:10