6

I found this thread: How to change annotation value at runtime using reflection?

And I'm trying to change method annotation, but java.lang.reflect.Method does not contain any map-field like "annotations" or method like "getDeclaredAnnotationMap"

There is only private byte[] annotations but what can I do with this byte array?

So, how to modify annotation of method?

EDIT:
I created that: http://pastebin.com/T2rewcwU
But that only edit this instance of method, if you uncomment 33 line of code then value will reset.

GotoFinal
  • 3,585
  • 2
  • 18
  • 33
  • 1
    Are you sure? http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getDeclaredAnnotations-- – Markus Patt Dec 29 '14 at 23:13
  • "map-field", and "getDeclaredAnnotation**Map**", that only copied array with annotations, nothing will change if you edit it. – GotoFinal Dec 29 '14 at 23:16
  • Oops, too late for me. I stopped reading after the JavaDocs "The caller of this method is free to modify the returned array". – Markus Patt Dec 29 '14 at 23:21
  • ok, I created that: http://pastebin.com/T2rewcwU , but this only edit current instance of Method class. – GotoFinal Dec 30 '14 at 00:07

1 Answers1

8

I wrote a class AnnotationUtil to resolve the seris requirements.

It can add/remove/change annotation value on class/field/method instance.

Note that use ReflectUtil to get root field/method when add/remove annotation.

See it on github:

AnnotationUtil

ReflectUtil

Dean Xu
  • 4,438
  • 1
  • 17
  • 44
  • 1
    I don't even remember why I needed this now, and I already know that trick (as I was only missing that root instance) but forgot about this question. Note that it will not work in next java versions, as they don't allow anymore for reflection between modules - additional jvm arguments will need to be used - or agent+instrumentation/unsafe/native code. I will accept this answer tho. – GotoFinal Nov 22 '17 at 19:47
  • @GotoFinal …and in case of class annotations, they’re held by a `SoftReference`, which allows garbage collecting the cached data and effectively revert your manipulations. – Holger Sep 07 '18 at 10:44
  • this is truly a last resort, but i learned a lot going through your utils :) – ekcrisp Sep 06 '19 at 16:12
  • Links are broken :( – Paul Praet Apr 29 '20 at 11:48
  • @PaulPraet Link is back. Enjoy! :) – Dean Xu Apr 29 '20 at 15:18
  • @DeanXu can you kindly please provide working example for using addAnnotation method for class methods, specifically the Annotation type parameter passed into the method – JayD Feb 26 '21 at 08:04
  • 1
    @JayD https://github.com/XDean/Java-EX/blob/master/src/test/java/cn/xdean/jex/reflect/AnnotationUtilTest.java – Dean Xu Feb 26 '21 at 08:09
  • @DeanXu cheers man, guess I didn't looked close enough – JayD Feb 26 '21 at 08:19