添加版权信息生成 java 代码 - Jcodemodel
Adding copyright info generated java code - Jcodemodel
我正在使用 JCodeModel 生成 java 源代码。我想将版权信息添加到生成的代码中。目前可以吗?
我尝试在 JDefinedClass 中使用 javadoc()
,它仅在 class 定义之上添加信息。
你可以创建一个CodeWriter
写版权header。此 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;
}
}
结果 class 将是
// Copyright 2017 - example.com
package com.example;
public class Example {
}
com.sun.codemodel.writer.PrologCodeWriter 正是您要找的
我正在使用 JCodeModel 生成 java 源代码。我想将版权信息添加到生成的代码中。目前可以吗?
我尝试在 JDefinedClass 中使用 javadoc()
,它仅在 class 定义之上添加信息。
你可以创建一个CodeWriter
写版权header。此 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;
}
}
结果 class 将是
// Copyright 2017 - example.com
package com.example;
public class Example {
}
com.sun.codemodel.writer.PrologCodeWriter 正是您要找的