我使用JCodeModel生成java源代码。我想在生成的代码中添加版权信息。这目前可能吗?
我尝试在JDefinedClass中使用javadoc()
,它只在类定义之上添加信息。
答案 0 :(得分:1)
您可以创建一个用于编写版权标题的CodeWriter
。这个CodeWriter
可以委托给另一个 - 也就是你通常传递给CodeModel#build
方法的那个。
一个完整的例子:
import java.io.IOException;
import java.io.OutputStream;
import com.sun.codemodel.CodeWriter;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.writer.SingleStreamCodeWriter;
public class HeaderInCodeModel
{
public static void main(String[] args) throws Exception
{
JCodeModel codeModel = new JCodeModel();
codeModel._class("com.example.Example");
CodeWriter codeWriter = new SingleStreamCodeWriter(System.out);
String header = "// Copyright 2017 - example.com\n";
CodeWriter codeWriterWithHeader =
createCodeWriterWithHeader(header, codeWriter);
codeModel.build(codeWriterWithHeader);
}
private static CodeWriter createCodeWriterWithHeader(
String header, CodeWriter delegate)
{
CodeWriter codeWriter = new CodeWriter()
{
@Override
public OutputStream openBinary(JPackage pkg, String fileName)
throws IOException
{
OutputStream result = delegate.openBinary(pkg, fileName);
if (header != null)
{
result.write(header.getBytes());
}
return result;
}
@Override
public void close() throws IOException
{
delegate.close();
}
};
return codeWriter;
}
}
结果类将是
// Copyright 2017 - example.com
package com.example;
public class Example {
}
答案 1 :(得分:1)
com.sun.codemodel.writer.PrologCodeWriter正是您想要的