joy87
joy87

Reputation: 25

How to assign method with multiple argument in Java CodeModel API

I want to generate a code like below example with Java CodeModel API

package com.testcase.myPackage; 
package com.aaa.abc; 
package com.bbb.b;
import org.testng.annotations.Test;

public class TestCode {         
    private int a;  
    private int b;  

    @Test   public void testMethod() throws excep1,excep2,excep3 {         
        a=abc.method1(b.param1,param2,param3);   
    } 
}

I already declared the class variable a & b, method testMethod with @Test annotation. Now I am stuck in the below point:

  1. Not able to throw multiple exceptions (throws excep1, excep2, excep3) in the method.

  2. Not able to invoke a method with multiple parameters & assign that invocation in class variable a = abc.method1(b.param1, param2, param3)

How do I resolve these issues?

Upvotes: 0

Views: 829

Answers (1)

John Ericksen
John Ericksen

Reputation: 11113

To declare multiple method exceptions and multiple method call parameters JCodeModel's API allows you to chain the call to add exceptions and parameters:

Exceptions:

testMethod._throws(Exception1.class)._throws(Exception2.class)._throws(Exception3.class);

Method parameters:

body.assign(a, abcRef.staticInvoke("method1").arg(param1Var).arg(param2Var).arg(param3Var));

For completeness, here's some code to generate the class close to your example:

JDefinedClass testCodeClass = codeModel._class(JMod.PUBLIC, "com.testcase.myPackage.TestCode", ClassType.CLASS);

JFieldVar a = testCodeClass.field(JMod.PRIVATE, codeModel.INT, "a");
JFieldVar b = testCodeClass.field(JMod.PRIVATE, codeModel.INT, "b");

JMethod testMethod = testCodeClass.method(JMod.PUBLIC, codeModel.VOID, "testMethod");
testMethod.annotate(Test.class);
testMethod._throws(Exception1.class)._throws(Exception2.class)._throws(Exception3.class);

JBlock body = testMethod.body();

JClass abcRef = codeModel.ref(abc.class);
JVar param1Var = body.decl(codeModel.INT, "param1", JExpr.lit(1));
JVar param2Var = body.decl(codeModel.INT, "param2", JExpr.lit(2));
JVar param3Var = body.decl(codeModel.INT, "param3", JExpr.lit(3));

body.assign(a, abcRef.staticInvoke("method1").arg(param1Var).arg(param2Var).arg(param3Var));

Which generates:

package com.testcase.myPackage;

import com.xxx.yyy.abc;
import org.junit.Test;

public class TestCode {

    private int a;
    private int b;

    @Test
    public void testMethod()
        throws Exception1, Exception2, Exception3
    {
        int param1 = 1;
        int param2 = 2;
        int param3 = 3;
        a = abc.method1(param1, param2, param3);
    }
}

Upvotes: 0

Related Questions