如何使用 javaparser 添加 class 级变量声明?

How to add class level variable declarations using javaparser?

class A{
    int x = 10;
}

这是A.java

我想要新的A.java

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

我想使用 javaparser 添加一个变量。

您需要这样做:

  1. 解析代码
  2. 找到要添加元素的点
  3. 添加你想要的元素
  4. 转回代码

第一点很简单,只需使用 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.

获得 class 声明后,您可以调用 addMember on it. In your example you are adding a field so you need to instantiate a FieldDeclaration

完成后,您将使用 CompilationUnit 并调用 toString。您将取回修改后的源代码。

来源:我是 JavaParser 提交者