2

我正在调查com.sun.codemodel生成 Java 类。

// https://mvnrepository.com/artifact/com.sun.codemodel/codemodel
compile group: 'com.sun.codemodel', name: 'codemodel', version: '2.6'

JCodeModel 类有多种构建方法,支持将所需的 Java 类生成到文件中,但是我想将这些生成的类作为字符串获取。

查看 JCodeModel 的 Javadoc 和源代码,我无论如何都无法实现这一目标。

如何获取生成的类作为字符串而不是/以及将它们写入文件?

是否可以扩展com.sun.codemodel.CodeWriter以产生字符串?

4

1 回答 1

3

当然!String由于 JCodeModel 生成多个类,因此只生成 a 有点棘手。您可以使用以下自定义查找这些类并将它们作为字符串输出CodeWriter

JCodeModel codeModel = new JCodeModel();

JDefinedClass testClass = codeModel._class("test.Test");
testClass.method(JMod.PUBLIC, codeModel.VOID, "helloWorld");

final Map<String, ByteArrayOutputStream> streams = new HashMap<String, ByteArrayOutputStream>();

CodeWriter codeWriter = new CodeWriter() {
    @Override
    public OutputStream openBinary(JPackage jPackage, String name) {
        String fullyQualifiedName = jPackage.name().length() == 0 ? name : jPackage.name().replace(".", "/") + "/" + name;

        if(!streams.containsKey(fullyQualifiedName)) {
            streams.put(fullyQualifiedName, new ByteArrayOutputStream());
        }
        return streams.get(fullyQualifiedName);
    }

    @Override
    public void close() throws IOException {
        for (OutputStream outputStream : streams.values()) {
            outputStream.flush();
            outputStream.close();
        }
    }
};

codeModel.build(codeWriter);

System.out.println(streams.get("test/Test.java"));

输出:

public class Test {


    public void helloWorld() {
    }

}
于 2018-01-17T05:27:13.040 回答