I'm trying to create an annotation that will change the content of the annotated field. So far this is my annotation:
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface MyAnnotation {
String value();
}
And I want to use it like this
public class MyClass {
@MyAnnotation("test")
String myField;
}
And then I want to set the value of myField to "test" at compile time. I just don't know how I can access the annotated field from my annotation processor and if it is even possible to change its content at compile time. This is what my annotation processor looks like right now:
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
annotations.stream().flatMap(a -> roundEnv.getElementsAnnotatedWith(a).stream())
.forEach(e -> {
if (!String.class.getName().equals(((VariableElement) e).asType().toString())) {
out.printMessage(Kind.ERROR
, "@MyAnnotation annotation can only be applied to Strings", e);
}
else {
// what to do here?
}
});
return true;
}
I am new to annotations and a little bit lost so any ideas are highly appreciated.
This should be easy using annotation processing, e.g. https://www.javacodegeeks.com/2015/09/java-annotation-processors.html