如何使用CodeModel从二级抽象超类调用方法?

时间:2013-08-26 23:51:53

标签: java code-generation sun-codemodel

我正在使用CodeModel 2.6。

当getType()方法从一个抽象超类继承时,我将如何生成这条指令,这两个级别高于JDefinedClass?

    assertEquals(GeneraldocumenMetadata.TYPE, generaldocumenMetadata.getType());

背景:

  1. assertEquals(...)方法来自“import static org.junit.Assert.assertEquals;”
  2. 类层次结构是
    • GeneraldocumenMetadata扩展了ItemMetadata
    • ItemMetadata扩展了AbstractItemMetadata
    • AbstractItemMetadata拥有getType()方法和私有类型字段
  3. 最终结果/所需方法如下:

    @Test
    public void testParameterizedConstructorSuccess()
    {
        String modifiedType = GeneraldocumenMetadata.TYPE + "andMore";
        generaldocumenMetadata = new GeneraldocumenMetadata(modifiedType);
    
        assertEquals(modifiedType, generaldocumenMetadata.getType());
    }
    

    CodeModel方法目前看起来像这样,但是“definedClass.getMethod(”getType“,new JType [] {});”返回null

    private void testDefaultConstructorMethod(JFieldVar uutField, JVar staticTYPEVar, final JDefinedClass unitTestClass, JDefinedClass definedClass, JCodeModel codeModel)
    {
        int modifiers = JMod.PUBLIC;
    
        JMethod unitTestMethod = unitTestClass.method(modifiers, Void.TYPE, "testDefaultConstructor");
        unitTestMethod.annotate(org.junit.Test.class);
    
        JBlock unitTestBody = unitTestMethod.body();
    
        unitTestBody.assign(uutField, JExpr._new(unitTestClass));
        JClass abstractItemMetadataClass = definedClass._extends();
    
        JMethod getTypeMethod = definedClass.getMethod("getType", new JType[] {});
        JExpr.invoke(getTypeMethod);
    
        JInvocation assertEqualsInvoke = codeModel.directClass("org.junit.Assert").staticInvoke("assertEquals").arg(staticTYPEVar).arg(JExpr.invoke(getTypeMethod));
        unitTestBody.add(assertEqualsInvoke);
    }
    

1 个答案:

答案 0 :(得分:2)

您需要调用该方法,而不是获取它,因为codeModel不会解析您定义的类:

JExpr.invoke(uutField, "getType");

这意味着您的代码模型代码如下所示:

private void testDefaultConstructorMethod(JFieldVar uutField, JVar staticTYPEVar, final JDefinedClass unitTestClass, JDefinedClass definedClass, JCodeModel codeModel)
{
    int modifiers = JMod.PUBLIC;

    JMethod unitTestMethod = unitTestClass.method(modifiers, Void.TYPE, "testDefaultConstructor");
    unitTestMethod.annotate(org.junit.Test.class);

    JBlock unitTestBody = unitTestMethod.body();

    unitTestBody.assign(uutField, JExpr._new(unitTestClass));
    JClass abstractItemMetadataClass = definedClass._extends();

    JInvocation assertEqualsInvoke = codeModel.ref(org.junit.Assert.class).staticInvoke("assertEquals").arg(staticTYPEVar).arg(JExpr.invoke(uutField, "getType"));
    unitTestBody.add(assertEqualsInvoke);
}