0

Does anybody know how to perform math operations in codeModel? I've been everywhere and can't figure it out. I have my generated class and I want e.g. add 2 variables(I've done it using Long.staticInvoke("sum"), but what I mean is adding,substracting,multiplying,division and all that stuff). Sample output I want to achieve:

class C {
    int a;
    int b;
    C() {
            a=5;
            b=7;
    }
    int foo() {
        return (a+b)/4*7;
    }
}

I have something like this:

try {
            String className = "C";
            JCodeModel model = new JCodeModel();
            JDefinedClass jdc = model._class(className);

            JFieldVar a = jdc.field(0, Integer.TYPE, "a");
            JFieldVar b = jdc.field(0, Integer.TYPE, "b");
            JMethod constructor = jdc.constructor(0);
            constructor.body().assign(a, JExpr.lit(5));
            constructor.body().assign(b, JExpr.lit(7));

            JMethod foo = jdc.method(0,Double.TYPE,"foo");
            foo.body()._return(/* WHAT GOES HERE? */);

            File file = new File("./src/types/");
            file.mkdirs();
            model.build(file);
        } catch(Exception e) {
            e.printStackTrace();
        }

any ideas?

John Ericksen
  • 10,995
  • 4
  • 45
  • 75
kcdsh
  • 59
  • 2
  • 11

1 Answers1

0

The JOp class will help you there. (a+b)/4*7 is generated by the following:

JOp.div(JOp.plus(a, b), JOp.mul(JExpr.lit(4), JExpr.lit(7)))
John Ericksen
  • 10,995
  • 4
  • 45
  • 75