问题
I'm using JExpr.plus()
method to form a String and syntactically it is correct, but it has a lot of brackets. For example:
JExpr.lit("ONE").plus(JExpr.lit("TWO")).plus(JExpr.lit("THREE"))
returns
(("ONE" + "TWO") + "THREE")
and I would like it to be
"ONE" + "TWO" + "THREE"
回答1:
It looks like with codemodel right now you cant avoid the addition of the parentheses. Plus (+) is considered a BinaryOp which generates its code with the following class:
Within com.sun.codemodel.JOp
:
static private class BinaryOp extends JExpressionImpl {
String op;
JExpression left;
JGenerable right;
BinaryOp(String op, JExpression left, JGenerable right) {
this.left = left;
this.op = op;
this.right = right;
}
public void generate(JFormatter f) {
f.p('(').g(left).p(op).g(right).p(')');
}
}
Notice the f.p('(')
and .p(')')
. The addition of the parentheses is baked into the code and cannot be avoided. That being said you could alter codemodel to do what you need, as it is open source. Personally, I don't see the need as the parentheses are useful in other circumstances.
来源:https://stackoverflow.com/questions/12961769/how-do-i-remove-unnecessary-brackets-using-codemodels-jexpr-plus-method