algorhythm
algorhythm

Reputation: 3426

JavaParser: get field name from FieldDeclaration

I've built up a list of FieldDeclarations and need to find out what the name of each field is:

List<FieldDeclaration> fields = classDeclaration.getFields();

for (FieldDeclaration field : fields)
{
    String fieldName = field.get...?
}

I can't find any methods that retrieve the name of the field.

Strangely though, one of the constructors does accept a field argument so not sure why it doesn't have a getter. Do I need to get it from another node?

FieldDeclaration(NodeList modifiers, Type type, String name) Creates a FieldDeclaration. https://www.javadoc.io/doc/com.github.javaparser/javaparser-core/3.15.1

Upvotes: 4

Views: 1514

Answers (1)

arkantos
arkantos

Reputation: 567

The constructor you mentioned is declared as this way

public FieldDeclaration(NodeList<Modifier> modifiers, Type type, String name) {
    this(assertNotNull(modifiers), new VariableDeclarator(type, assertNotNull(name)));
}

In the source code of FieldDeclaration, there is a nodelist of VariableDeclarators as follows;

@NonEmptyProperty
private NodeList<VariableDeclarator> variables;

And you can get this private list with following method;

public NodeList<VariableDeclarator> getVariables() {
    return variables;
}

Once you get your list, you should use VariableDeclarator class methods, if you look at it's source code this method should work;

@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
    return name;
}

EDIT

You can access source codes here

Upvotes: 4

Related Questions