0

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?

Diamond
  • 7,428
  • 22
  • 37
joy87
  • 25
  • 4

1 Answers1

0

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);
    }
}
mkj
  • 2,761
  • 5
  • 24
  • 28
John Ericksen
  • 10,995
  • 4
  • 45
  • 75
  • For method invocation i don't want org.parceler.Tester.ABC abc = new org.parceler.Tester.ABC(); line. I just want to import abc ( import com.xxx.yyy.abc ) & use to invoke method ( abc.method(p1,p2,p3) ) – joy87 Jul 27 '15 at 07:07
  • Ok, I'll assume that means abc is a static class. (FYI, this violates the standard Java class naming convention) – John Ericksen Jul 27 '15 at 12:17