0

I'm trying to update the method annotation value in a java file at runtime. I'm able to update the value and finally, I got the changes. But don't know how to write the updated source code to file. I'm assuming all changes are present in forName. So please let me know any solution to write the modified java source code to file.

try {
    Class<?> forName = Class.forName("test.SortJsonContent");
    Method[] methods = forName.getDeclaredMethods();
    for (Method method : methods) {                
        method.setAccessible(true);
        if (method.isAnnotationPresent(AnnoTest.class)) {
            AnnoTest anno = method.getAnnotation(AnnoTest.class);
            changeAnnotationValue(anno, "test", "new val");                    
        }
    }
} catch (Exception e) {
    System.err.println("error"+ e);
}
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
kumar
  • 11
  • 1
  • You should probably use a bytecode parser / writer (like [ASM](https://asm.ow2.io/)) for this. – Johannes Kuhn Apr 20 '20 at 16:32
  • Seems I need to rewrite the whole implementation. Is there any way which accepts the updated java.lang.Class and write to a file? – kumar Apr 20 '20 at 16:43
  • No. Not that I am aware of. – Johannes Kuhn Apr 20 '20 at 16:48
  • 1
    1) `method.setAccessible(true);` is obsolete here 2) you didn't show what `changeAnnotationValue(anno, "test", "new val");` actually does. Since there is no way to change a `Class` via Reflection, this is likely one of those hacks which manipulates internal data structures to make it pretend changed annotation values and even that unreliably. In that case, it didn't change the class and there is no way to write back what doesn't allow changes. 3) If you want to "write the updated *source code*" you are even farther away from your goal. There is no source code at runtime. – Holger Apr 22 '20 at 20:40

0 Answers0