Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get static FIELD value using annotation processing

It sounds like a simple question, but I cannot manage to make it work in Android.

What Ive got is a simple annotated field:

@MyAnnotation
public static final String TEXT = getText();

private static final String getText(){
    return "TEXT";
}

I made an annotation processer to process @MyAnnotation, but I found out that it is not possible to read value of field using annotation processor. I have also tried reflection, but reflection is only available at runtime ..

I need that field value for code generation based on it.

It is possible to read value of field using annotation processing ? If not is there any way to achieve this ?

like image 264
spili Avatar asked Nov 30 '25 22:11

spili


1 Answers

public class CompileTimeAnnotationProcessor extends AbstractProcessor{
 ...
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
      // Only one annotation, so just use annotations.iterator().next();
    Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotations.iterator().next());
    Set<VariableElement> fields = ElementFilter.fieldsIn(elements);
    for (VariableElement field : fields) {
        field.getConstantValue();  //get the value of static field?
    }
    return true;
 }
 ...
}

the method getConstantValue() may help you.

Returns the value of this variable if this is a {@code final} field initialized to a compile-time constant.

like image 134
刘奔康 Avatar answered Dec 03 '25 12:12

刘奔康