0

I wrote this simple annotation:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface CSVColumn {
    String name();

    int order();
}

which I'm currently using to annotate some getter methods of a class. I'm able to get the values of this annotation at runtime:

    Class classType = objects[0].getClass();
    Method[] methodsArray = classType.getDeclaredMethods();
    List<Method> methods = Arrays.asList(methodsArray);
    //FIlter annotated methods
    methods = methods.stream().filter(method -> method.getAnnotation(CSVColumn.class) != null).collect(Collectors.toList());

    Iterator<Method> methodIterator = methods.iterator();

    while (methodIterator.hasNext()) {
        Method method = methodIterator.next();
        CSVColumn csvColumn = method.getAnnotation(CSVColumn.class);
        String header = csvColumn.name();
    }

but how could I set the field name of the annotation to another value? Should/could I declare some setter methods in the annotation class?

1Z10
  • 2,801
  • 7
  • 33
  • 82
  • Possibly related: https://stackoverflow.com/questions/14268981/modify-a-class-definitions-annotation-string-parameter-at-runtime – assylias Mar 15 '18 at 10:04
  • 1
    Even though it may be possible to change annotations at runtime by digging in the JVM internals, you're really not supposed to do that. You need to come up with a different data structure for storing the information you need to change at runtime. – yole Mar 15 '18 at 10:05

1 Answers1

0

Use the utility class AnnotationUtil

You can do changeAnnotation(csvColumn, "name", "newName")

Dean Xu
  • 4,438
  • 1
  • 17
  • 44
  • Thanks man, I will have a lot to learn from your repo. It's an awesome work, congratulations. – 1Z10 Mar 15 '18 at 19:11