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?
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);