How to generate loops and conditionals using the codemodel library
java, sun-codemodel
Solution
Im going to assume you already have a class and method defined.
To write a condition if/else statement you need to use the `_if()` and `_else()` methods on the `JBody` class. This adds the statement to the body of the method you have defined. from these methods you can reference and add to their bodies by calling the `_then()` method on the `_if()` or `_else()` returns the `JBody` directly. Here's an example:
JConditional condition = body._if(input.lt(JExpr.lit(42)));
condition._then().add(
codeModel.ref(System.class).staticRef("out").invoke("println").arg(JExpr.lit("hello")));
condition._else().add(
codeModel.ref(System.class).staticRef("out").invoke("println").arg(JExpr.lit("world")));
which outputs:
if (input< 42) {
System.out.println("hello");
} else {
System.out.println("world");
}
To write a for loop, there are a couple of options. The traditional for loop is written using the `_for()` method on the JBlock, which allows you to chain the `init()`, `test()` and `update()` methods corresponding to the various parts of the for loop declaration:
JForLoop forLoop = body._for();
JVar ivar = forLoop.init(codeModel.INT, "i", JExpr.lit(0));
forLoop.test(ivar.lt(JExpr.lit(42)));
forLoop.update(ivar.assignPlus(JExpr.lit(1)));
forLoop.body().add(
codeModel.ref(System.class).staticRef("out").invoke("println").arg(ivar));
which outputs:
for (int i = 0; (i< 42); i += 1) {
System.out.println(i);
}
For kicks, here's a working example: https://gist.github.com/johncarl81/7647146
Problem
I've been trying to learn how to use Suns codemodel library and I'm absolutely stumped with generating for loops and if-else blocks. I'm struggling with how to generate the conditions for the if-else blocks and the for loops, but also on how to generate the body of these as well. For example: ``` if (condition) { //How is this condition generated? //How is this body filled? } else { } ``` For the loop: ``` for(condition) { //How is this condition generated? //How is this body filled? } ```