简体   繁体   English

注释处理 - 如何访问(和修改)字段的内容

[英]annotation processing - how to access (and modify) the contents of a field

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.然后我想在编译时将 myField 的值设置为“test”。 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.我是注释的新手,有点迷失,所以任何想法都受到高度赞赏。

这应该很容易使用注释处理,例如https://www.javacodegeeks.com/2015/09/java-annotation-processors.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM