Richard Pianka Richard Pianka - 1 year ago 68
Java Question

Modify a class definition's annotation string parameter at runtime

Imagine there is a class:

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

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?

Answer Source

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

  • a proper implementation needs to also deal with the declaredAnnotations
  • if the implementation of annotations in changes, the code will break (i.e. it can break at any time in the future)
  • I have no idea if there are side effects...


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() {

        public String someProperty() {
            return "another value";

        public Class<? extends Annotation> annotationType() {
            return oldAnnotation.annotationType();
    Field field = Class.class.getDeclaredField("annotations");
    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 {

@interface Something {

    String someProperty();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download