Search code examples
javasun-codemodel

How do I remove unnecessary brackets using CodeModel's JExpr.plus method?


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"

Solution

  • 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.