如何使用codemodel库生成循环和条件

时间:2013-11-25 04:01:15

标签: java sun-codemodel

我一直在努力学习如何使用Suns codemodel 库,我绝对不会为生成 for loop和if-else块而烦恼。我正在努力如何为if-else块和for循环生成条件,还要讨论如何生成这些条件的主体。

例如:

if (condition) { //How is this condition generated?
     //How is this body filled?
} else {

} 

对于循环:

for(condition) {  //How is this condition generated?
   //How is this body filled?
}

1 个答案:

答案 0 :(得分:4)

我假设您已经定义了一个类和方法。

要编写条件if / else语句,您需要使用_if()类上的_else()JBody方法。这会将语句添加到您定义的方法的主体中。从这些方法中,您可以通过调用_then()上的_if()方法或_else()直接返回JBody来引用并添加到自己的实体中。这是一个例子:

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

输出:

if (input< 42) {
    System.out.println("hello");
} else {
    System.out.println("world");
}

要编写for循环,有几个选项。传统的for循环是使用JBlock上的_for()方法编写的,它允许您链接对应于for的各个部分的init()test()update()方法。循环声明:

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

输出:

for (int i = 0; (i< 42); i += 1) {
    System.out.println(i);
}

对于踢球,这是一个有效的例子:https://gist.github.com/johncarl81/7647146

相关问题