本文介绍了如何使用CodeModel的JExpr.plus方法删除不必要的括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JExpr.plus()方法形成一个String,从语法上讲它是正确的,但是它有很多括号.例如:

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"))

返回

(("ONE" + "TWO") + "THREE")

我希望成为

"ONE" + "TWO" + "THREE"

推荐答案

使用代码模型现在看来,您无法避免添加括号.加号(+)被认为是BinaryOp,它使用以下类生成其代码:

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:

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(')');
    }

}

注意f.p('(').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.

这篇关于如何使用CodeModel的JExpr.plus方法删除不必要的括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:21