1

Is there a way modify the attributes of Field annotations at runtime? Not just the annotation object you can get from a Field at any one point, but whenever in the future you get the same annotation it is updated with the new values.

My task is to be able to at runtime compile a Java file and then use that Class in the application. I've done that, but the only problem is that while in a standard Java application custom annotations do get saved, they are for some reason stripped when run on a Spring application running on Tomcat 7. This is all in memory compilation BTW, no files are ever created in the process.

I couldn't find any way to solve that issue, so I decided to just parse the Java file a second time and add annotations to whatever fields I needed to. I figured out how to add an annotation to a field which didn't have any before through some hacks, but now I need to configure it, seeing as the annotation has some attributes, several booleans and an int.

I've looked into several ways provided in a lot of StackOverflow questions, but they all modify the annotation object that you obtain through reflection, and if I in another method try to get the same annotation, it's values are reset. Any insight into the matter would be greatly appreciated.

  • No, annotation attributes are constants. – Sotirios Delimanolis Jul 16 '15 at 15:28
  • You can edit them in the Annotation object. The Field class also has a private field called annotations, which is a byte array containing annotation data. That's how I added annotations to fields, but creating a byte array that corresponds to the correct annotation with all the settings has been fairly difficult. – Michael Dimchuk Jul 16 '15 at 15:29
  • 1
    The `Field` case is an implementation detail. Do not depend on it. I don't know what you mean by _You can edit them in the Annotation object._. – Sotirios Delimanolis Jul 16 '15 at 15:31
  • Unfortunately I don't have a choice but to make this work. By editing the Annotation object I mean that I found one implementation where you edit the value map stored in a proxy invocation object, containing the attribute information for the annotation. Unfortunately that doesn't propagate and thus is only saved in the local object. – Michael Dimchuk Jul 16 '15 at 15:36
  • The way to edit an Annotation object is presented here: http://stackoverflow.com/a/28118436/5124223 – Michael Dimchuk Jul 16 '15 at 15:43

1 Answers1

0

For anyone viewing this in the future, I solved the problem by first compiling my code and getting the bytecode before it is created into a class. Then I used Javassist to add annotations at runtime. After that I just compiled it into a class through a custom class loader, which got me the Class object without loading it into the system class loader.