0

I try to add new FieldDeclarations to my Main Class in CompilationUnit before all other existing FieldDeclarations.

mainClassInCompilationUnitDeclaration.addPrivateField("Type", "fieldName");

Where mainClassInCompilationUnitDeclaration is a ClassOrInterfaceDeclaration representing the first declared Class in the CompilationUnit.

Unfortunately, all added Declarations get serialized on the end of the class. This is logical as the elements are added at the end of the tree.

How can I change where they get added? Is there any "insertBefore" in Javaparser?

Daria Pydorenko
  • 1,754
  • 2
  • 18
  • 45
StefanLe
  • 11
  • 3
  • 1
    In the meanwhile i found out that i can add new Members before existing ones via `mainClassInCompilationUnitDeclaration.getMembers().addFirst(field);` and `mainClassInCompilationUnitDeclaration.getMembers().addAfter(field, lastField);`. The Methods `addFirst` and `addAfter` are declared by `NodeList` which is not exposed by all Elements, so i cant use it for `LineComment`s for example as well. – StefanLe Aug 20 '18 at 11:04
  • You can also use the method add with a positional index. – jpl Jul 12 '23 at 09:59

1 Answers1

0

I think you have to make a work around to handle this case for example you can make these steps:

  1. Get the existing elements and save them in another reference and remove them from your compilation unit .

  2. Add the new elements you have made

  3. Add the old elements again to your compilation unit

by doing that you now have the desired order.

Eslam Ashour
  • 113
  • 12