Установить значение поля по аннотации
Я хочу установить значение переменной по аннотации.
У меня есть следующий код:
public class Foo {
@AutoProperty
private String bar;
//...
}
Аннотация определяется следующим образом:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public @interface AutoProperty {
}
И AnnotationProcessor это:
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class AutoPropertyProcessor extends AbstractProcessor {
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> annotations = new LinkedHashSet<String>();
annotations.add(AutoProperty.class.getCanonicalName());
return annotations;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (TypeElement annotation : annotations) {
Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotation);
Set<VariableElement> fields = ElementFilter.fieldsIn(elements);
for (VariableElement field : fields) {
String className = ((TypeElement) field.getEnclosingElement()).getQualifiedName().toString();
writeFieldValue(className, field);
}
}
return true;
}
private void writeFieldValue(String className, VariableElement field) {
String packageName = null;
int lastDot = className.lastIndexOf('.');
if (lastDot > 0) {
packageName = className.substring(0, lastDot);
}
String simpleClassName = className.substring(lastDot + 1);
// How would one set the Value of `field` to "foo"?
}
}
Как я могу установить значение bar
поле в пределах writeFieldValue
-метод? Все, что я нашел, - это как создать новый файл Class из AnnotationProcessor, но нет информации о том, как изменить существующий код.
Я хотел использовать JavaPoet для модификации кода, если это возможно.