1

Class MyClass has a numeric field number with annotations.

class MyClass {

    @Min(10)
    Number number;
}

I would like to use reflection and add a new annotation @Max(20) to the field on runtime.

How?

I have read an article https://www.baeldung.com/java-reflection-change-annotation-params, I could not find annotationData. There is not public method see or append or put annotation.

I use open-jdk-10.

I found here. I would like to close my question. Adding Java Annotations at Runtime

Yan Khonski
  • 12,225
  • 15
  • 76
  • 114
  • "I found here" Yes, and how does that *not* answer your question? – Michael Feb 18 '19 at 11:18
  • There might be easier ways to achieve what you want depending on how the annotations are used at runtime. As an example, some frameworks (like Hibernate) maintain an internal configuration and allow you to use xml or annotations to configure your classes. In that case changing the annotation value or adding an annotation at runtime might not work anyways (because it might happen too late) and thus you'd need to make the changes to the resulting configuration that might be stored elsewhere ... – Thomas Feb 18 '19 at 11:23
  • In other cases, like CDI, there are facilities to add information at load time (CDI would make use of extensions for that) and that way you could add "annotations" (those would not be available to reflection but would be visible to CDI via its internal configuration store). – Thomas Feb 18 '19 at 11:25

1 Answers1

3

As it has been specified in this answer already it is not possible by a normal java means. You can use AOP though and through byte code instumentntion you can add an annotation Adding Java Annotations at Runtime

Alexander Petrov
  • 9,204
  • 31
  • 70