将Roaster生成的java类替换为相应的包

时间:2015-04-20 10:10:13

标签: java jboss

我正在搜索从输入生成Java源代码的API,我发现了几乎像Roaster JBoss和CodeModel这样的api。但我的目标是生成Java Source并将其放在approriate Packages中。对于Roaster API,它生成我正在寻找的代码,但仅限于显示它。对于codemodel生成器,我可以将生成的代码替换为文件,但我应该手动替换它们。

CodeModel示例:

    JCodeModel cm = new JCodeModel();
    JDefinedClass dc = cm._class("Exemple");
    JFieldVar fv = dc.field(0, String.class, "Name");
    File file = new File("./file/classes");
    file.mkdirs();
    cm.build(file);

Roaster示例:

final JavaClassSource javaClass = Roaster.create(JavaClassSource.class);
    javaClass.setPackage("com.soprasteria.toolsandmeasures.modeling.loading").setName("Main");

    javaClass.addInterface(Serializable.class);
    javaClass.addField()
      .setName("serialVersionUID")
      .setType("long")
      .setLiteralInitializer("1L")
      .setPrivate()
      .setStatic(true)
      .setFinal(true);

    javaClass.addProperty("Integer", "id").setMutable(false);
    javaClass.addProperty("String", "firstName");
    javaClass.addProperty("String", "lastName");

    javaClass.addMethod()
      .setConstructor(true)
      .setPublic()
      .setBody("this.id = id;")
      .addParameter(Integer.class, "id");
    System.out.println(javaClass);

任何人都可以帮助我!

1 个答案:

答案 0 :(得分:0)

您可以保存在java类中生成的内容。

一个例子:

public void createClass() {
    final JavaClassSource javaClass = Roaster.create(JavaClassSource.class);
    javaClass.setPackage("com.company.example").setName("Person");

    javaClass.addInterface(Serializable.class);
    javaClass.addField().setName("serialVersionUID").setType("long").setLiteralInitializer("1L").setPrivate()
            .setStatic(true).setFinal(true);

    javaClass.addProperty(Integer.class, "id").setMutable(false);
    javaClass.addProperty(String.class, "firstName");
    javaClass.addProperty("String", "lastName");

    javaClass.addMethod().setConstructor(true).setPublic().setBody("this.id = id;").addParameter(Integer.class,
            "id");

    try {
        File file = new File("src/main/java/" + "com.company.example" + "/" + "Person" + ".java");
        file.getParentFile().mkdirs();
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(javaClass.toString());
        bw.close();
    } catch (IOException e) {

    }
}

我正在创建一个旨在创建类的项目。如果你想看到:

https://github.com/robsonbittencourt/fixture-generator