Search code examples
javapluginssun-codemodel

JExpression add String value as property in an if statement


I am working on a plugin to create toString statements in my project, using CodeModel.

The resulting code should look like this:

if (variable == null) { 
    out.append("   " + "variable = null").append("\n"); 
}

(out in the code above is a simple StringBuilder)

I want to use CodeModel to automatically generate new lines and tabs in the if statements, and have so far got up to this output:

if ("variable" == null) { 
    out.append("   " + "variable = null").append("\n"); 
}

The issue is the quotes surrounding the variable, which are there as I assign a JExpression literal value for the variable value. Current implementation looks like this:

    private void printComplexObject(final JMethod toStringMethod, FieldOutline fo) {
        String property = fo.getPropertyInfo().getName(false);
        property = property.replace("\"", "");

        JType type = fo.getRawType();
        JBlock block = toStringMethod.body();
        JConditional nullCheck = block._if(JExpr.lit(property).eq(JExpr._null())); ...}

Is anyone aware of how this could be done using JExpression or anything else from CodeModel? The only alternative I have so far is to do it with a directStatement as follows:

toStringMethod.body().directStatement("if (" + property + " == null) { out.append ...}");

Solution

  • The solution is to replace the JConditional nullCheck with the following:

    JConditional nullCheck = block._if(JExpr.direct(property).eq(JExpr._null()));

    JExpr.direct(property) instead of .lit results in variable instead of "variable" being used in this JConditional.