Search code examples
javajavaparser

How to generate field and initialize value


How to initialize a field that is generated. Or in the code example below, where can the AssignExpr object be added for the code to work?

private void addConfigField(ClassOrInterfaceDeclaration clazz) {
    var className = "BlaConfig";
    var configField = clazz.addField(className, "blaConfig", Modifier.PRIVATE);
    var configFieldExpr = new NameExpr("blaConfig");

    var newConfigObj = new ObjectCreationExpr(null, JavaParser.parseClassOrInterfaceType(className), new NodeList<>());
    var assign = new AssignExpr(configFieldExpr, newConfigObj, Operator.ASSIGN);
}

Using com.github.javaparser:javaparser-core:3.2.4


Solution

  • You can get the variable declared in the 'configField'. That variable may be initialized.

    configField.getVariable(0).setInitializer(/* Your code */);