Adam
Adam

Reputation: 163

Java Annotation Processing - Get Constructor Value

Is it possible to get the value of an enum constant's constructor argument within an annotation processor?

I have an enum which defines a constructor and is scanned because it is also annotated.

@MyAnnotation
public enum Exmaple{
    FOO("foo value"),
    BAR("bar value");

    Example(final String val){}
}    

I'd like to be able to get the values of the constructor arguments that the constants define (i.e actually know that the constant FOO is initialized with "foo value"). Is this possible?

I can find each constant but there are no enclosed elements so the actual TypeElement which the enum constant is, seems to be the end of the line.

Any help would be great!

Upvotes: 5

Views: 689

Answers (1)

Cause Chung
Cause Chung

Reputation: 1505

Given below enum:

public enum EnumSize {
    SMALL(1), MEDIUM(2), LARGE(3);

    private final int size;
}

We can use Tree API to get the statement:

var trees = Trees.instance(processingEnv);
VariableElement enumConstant = // get from enclosing elements
trees.getTree(enumConstant) // here you go:
/*public static final*/ SMALL /* = new EnumSize(1) */ /*enum*/ (1)

Upvotes: 0

Related Questions