Bite
Bite

Reputation: 21

Javaparser add new field to class

I would like to add a new field of type List to every existing field in a class. I would also like it to be initialized with an empty ArrayList<Long>. How can I create the appropriate FieldDeclaration object to add to list of BodyDeclaration in the class (TypeDeclaration) I've already extracted?

Upvotes: 1

Views: 1235

Answers (1)

Allen
Allen

Reputation: 31

I know this is kind of old and you might already found an answer but since there is no answer here and this has troubled me some time before I found a way to do it so I will write down how I solved this problem.

Note: On JavaParser's FAQ it explicitly states that it's intended to either use lazy initialization (in either getter or setter) to an empty list. For more information on this please refer to the following issue:

Without further ado, here is how I worked around it:

String initString = "ArrayList<" + argType + ">()";
FieldDeclaration fd = new FieldDeclaration(
                            ModifierSet.PUBLIC, 
                            new ClassOrInterfaceType(className), 
                            new VariableDeclarator(
                                new VariableDeclaratorId(name, new NameExpr(initString))));

Where className is the collection's name (List in this case) and initialize another ClassOrInterfaceType instance to add argType. Then fd will produce the following:

public List<argType> parameters = new ArrayList<argType>();

Upvotes: 3

Related Questions