1

I want to generate some very common code using Sun's CodeModel

while ((sbt = reader.readLine()) != null)
{

}

However when I write:

JWhileLoop whileJsonBuilder = block._while(JExpr
                            .ref("partJsonString").assign(JExpr.ref("reader"))
                            .ne(JExpr._null()));

I get

while (partJsonString = reader!= null) {
    stringBuilder.append(partJsonString);
}

Notice that the brackets are missing. How can I force brackets to appear in the code?

Illidanek
  • 996
  • 1
  • 18
  • 32
druk
  • 553
  • 6
  • 16
  • `for (;;) { String sbt = reader.readLine(); if (sbt == null) break; ... }` is feasible in CodeModel. There is no reason to prefer that while pattern as being better style, contrary. – Joop Eggen Sep 25 '14 at 11:31
  • Yeah, thanks. But I was thinking that there would be a way to achieve while in codeModel, afterall it is written by Sun. – druk Sep 25 '14 at 11:52
  • There seems to be only a subset of assign statements for instance. I sought quickly after comma-expression too - to no avail. – Joop Eggen Sep 25 '14 at 12:24

1 Answers1

1

Unfortunately I was unable to find a preexisting way to add parenthesis. You can, however, extend JCodeModel to handle this by adding a special JExpression to render the paraenthesis:

public class ParensExpession extends JExpressionImpl{

    private JExpression expression;

    public ParensExpession(JExpression expression) {
        this.expression = expression;
    }

    @Override
    public void generate(JFormatter formatter) {
        formatter.p('(').g(expression).p(')');
    }
}

Incorporated into your code:

JWhileLoop whileJsonBuilder = block._while(
    new ParensExpession(
        JExpr.ref("partJsonString").assign(JExpr.ref("reader"))
    ).ne(JExpr._null()));

Gives:

while ((partJsonString = reader)!= null);
John Ericksen
  • 10,995
  • 4
  • 45
  • 75