1

I need to change one of the custom annotation field at Runtime (Java 7) from another class. As its not a problem to access the annotation field for given method, a cannot discover how to change value of fields in annotation (if its possible).

I have such implementation of annotation:

@Target({ElementType.METHOD}) 
@Retention(RUNTIME)
public @interface Something {

public String description() default "";

public boolean required() default false;

public int sortOrder() default -1;

}

In java class XYZ I have annotated many methods and define annotation fields such as:

@Something(description="name",required=true, sortOrder=1)
String getName();
void setName(String name);

@Something(description="address",required=true, sortOrder=1)
String getAddress();
void setAddress(String address); 

Finally, in another class I need to change some values of annotation for annotated method in certain conditions, for example required from true to false for method getAddress(). I grab annotation data like this:

try{
    Method method = XYZ.class.getDeclaredMethod("getAddress", null);
    method.setAccessible(true);
    Something ann = method.getAnnotation(Something.class);
    String name = ann.description();
} catch (Exception e) {
    e.printStackTrace();
}

I'm stuck with this as found how to change value for annotations with only one field.

PS. Sorry for my English...

Guillaume S
  • 1,462
  • 2
  • 19
  • 31
  • Possible duplicate of [Modify a method annotation parameter at runtime](https://stackoverflow.com/questions/27697358/modify-a-method-annotation-parameter-at-runtime) – GotoFinal Sep 04 '18 at 08:55
  • Possible duplicate of [Modify a class definition's annotation string parameter at runtime](https://stackoverflow.com/questions/14268981/modify-a-class-definitions-annotation-string-parameter-at-runtime) – Dean Xu Sep 04 '18 at 08:57
  • @DeanXu why you linked to editing class annotation? This is a bit different case - with different code needed to modify it. I think that your answer on my question is better match. – GotoFinal Sep 04 '18 at 09:03
  • @GotoFinal Thanks, however I saw these topics before and solutions do work on Java 8. I'm looking for solution for Java 7 that does not implement Java 8 features, like lambdas. – Sebastian Jakubiak Sep 04 '18 at 10:22
  • @boobsj this should work on java 7, just replace lambdas with old good anonymous classes etc. – GotoFinal Sep 04 '18 at 11:14
  • 1
    Annotations are modifiers, just like `public` or `final`. They are not meant to be modified and any “solution” that appears to modify an annotation, is just a hack modifying a particular runtime data structure which reports the content of the actual annotation. These hacks are unreliable even within one runtime and may break even more in newer Java versions or alternative implementations, whose internal data structures are different. – Holger Sep 07 '18 at 09:44

0 Answers0