2

我有一个 java 类说 Class A 已经存在一些方法,我正在使用代码模型生成一个类classB,并且在使用代码模型生成时我试图调用一个方法classA

我在下面试过

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

但它不起作用,如果有人知道如何做同样的事情,我将不胜感激

我想生成一个方法,如:

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

我也对如何生成以下方法感兴趣:

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

}
4

1 回答 1

1

让我们从:

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

假设您已经有一个JMethod method,您首先需要创建一个helper实例:

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

然后只需在其上调用所需的方法:

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

没有这个:

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

它更容易,您只需要进行静态调用。类似的东西:

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

如果您对注释感兴趣:

method
    .annotate(Test.class);

请注意,在上面的调用中,我可以arg直接将字符串传递给方法(arg("message"))。这只是字符串的一种方便方法。如果你想使用其他类型,比如原始类型,你需要做一些类似JExpr.lit(12.34).

于 2018-06-29T10:28:56.017 回答