Hello, i am trying to write a rule that will check if an Entity class is annotated with @ApiModel, i have done that now i want the same rule to check for the members of that class, If they are of type variable they must be annotated with @ApiModelProperty , I have accessed them using classTree.members() but i can’t access classTree.members().modifiers although the values that I need to check are there while debugging.
i would like to know how to access these values from classTree, thank you!
modifiers is part of the interface VariableTree, while ClassTree.members contains components of the more general type Tree. The not so good solution would be to do a type check and type cast:
// since Java 14
if (member instanceof VariableTree variable) {
...
}
// before Java 14
if (member instanceof VariableTree) {
VariableTree variable = (VariableTree) member
....
}
// or:
if (member.is(Tree.Kind.VARIABLE)) {
VariableTree variable = (VariableTree) member
....
}
Better approach:
You should not manually traverse the AST nodes and dispatch the types. We have tree visitors for that:
public class MyCheck extends BaseTreeVisitor {
@Override
public void visitClass(ClassTree tree) {
// check presence of you annotation
}
@Override
public void visitVariable(VariableTree tree) {
// check presence of you annotation
}
}