javasun-codemodel

How to call a method of another class using codemodel


I have a java class say Class A with some methods already present, I am generating a class using code model say classB and while generating using code model I am trying to call one the method of that classA.

i tried below

method
    .body()
    .invoke(JExpr.ref(helper), "display")
    .arg("hello");

but it is not working, I will really appreciate if someone knows how to do the same

I want to generate a method like:

public void method() { 
    Helper helper = new Helper(); 
    helper.display("hello") 
}

I am also interested in how I can generate the following method:

@Test 
public void method() { 
    Assert.fail("message") 

}

Solution

  • Let's start with:

    public void method() { 
        Helper helper = new Helper(); 
        helper.display("hello") 
    }
    

    Assuming you already have a JMethod method, you first need to create a helper instance:

    JVar helper = method
        .body()
        .decl(
            codeModel.ref(Helper.class),
            "helper",
            JExpr._new(codeModel.ref(Helper.class)));
    

    Then just invoke the desired method on it:

    method
        .body()
        .invoke(helper, "display")
        .arg("hello");
    

    No this one:

    @Test
    public void method() { 
        Assert.fail("message") 
    }
    

    It's even easier, you only have to do a static invocation. Something along the lines:

    method
        .body()
        .staticInvoke(codeModel.ref(Assert.class))
        .arg("message");
    

    If you're interested in the annotation:

    method
        .annotate(Test.class);
    

    Note that in the invocations above I could pass strings to the arg method directly (arg("message")). This is just a convenience method for strings. If you want to use other types like primitve types, you will need to do something like JExpr.lit(12.34).