0

我正在使用 JCodeModel 生成 java 源代码。我会在生成的代码中添加版权信息。目前这可能吗?

我尝试javadoc()在 JDefinedClass 中使用,它仅在类定义上方添加信息。

4

2 回答 2

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 {


}
于 2017-12-24T15:58:45.127 回答
1

com.sun.codemodel.writer.PrologCodeWriter 正是您正在寻找的

于 2018-11-14T02:31:30.987 回答