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

╄→尐↘猪︶ㄣ 提交于 2019-12-11 11:40:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!