3
class A{
    int x = 10;
}

This is A.java

I want to get NewA.java

class NewA{
    int x = 10;
    Sting text = "B";
}

I want to add a variable using javaparser.

HooMin.Lee
  • 115
  • 1
  • 8

1 Answers1

0

You need to do this:

  1. Parse the code
  2. Find the point where you want to add your element
  3. Add the element you want
  4. Dump back the code

The first point is trivial, just use the JavaParser.parse method. You will get a CompilationUnit. In the example you shown you are adding a field in a class declaration, so you need first to get that class declaration. Call getTypes and look into that list for the declaration you want or just call getClassByName.

Once you have your class declaration you can call addMember on it. In your example you are adding a field so you need to instantiate a FieldDeclaration.

Once you are done you take your CompilationUnit and call toString. You will get back the modified source code.

Source: I am a JavaParser committer

Federico Tomassetti
  • 2,100
  • 1
  • 19
  • 26