【问题标题】:Add import using code model使用代码模型添加导入
【发布时间】:2015-08-28 06:49:41
【问题描述】:

我正在尝试使用代码模型在我的代码中导入一个类。 这是我的代码。

JCodeModel model = new JCodeModel();
JClass mapper = model.directClass("com.another.Mapper");
JDefinedClass dc = model._class("com.example.Something");
JMethod method = dc.method(JMod.PUBLIC | JMod.STATIC, Void.TYPE,
        "testMethod");
JBlock executerBlock = method.body();
    executerBlock.directStatement("Mapper.get()");
File file = new File("./src");
file.mkdirs();
model.build(file);

现在我得到以下课程。

package com.example;
public class Something {
    public static void testMethod() {
    Mapper.get()
    }
}

但实际上我需要的是,

package com.example;
import com.another.Mapper;
public class Something {
    public static void testMethod() {
    Mapper.get()
    }
}

除非使用,否则导入不会到来。我怎样才能进行此导入。

【问题讨论】:

  • 如果不使用导入,则不在.class中。这是创建正确源代码的工具。看起来像一个功能。为什么要以其他方式?
  • @Jayan 我正在使用 JBlock.directStatement() 方法。在里面我正在使用这个类。(有问题更新)。

标签: java sun-codemodel jcodemodel


【解决方案1】:

要将Mapper 添加为导入,您需要调用invoke() / staticInvoke() 而不是directStatement()

JClass mapper = model.directClass("com.another.Mapper");
JDefinedClass dc = model._class("com.example.Something");
JMethod method = dc.method(JMod.PUBLIC | JMod.STATIC, Void.TYPE, "testMethod");
JBlock executerBlock = method.body();
executerBlock.staticInvoke(mapper, "get");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多