Adding copyright info generated java code - Jcodemodel

329 views Asked by At

I am generating java source code using JCodeModel. I would to add copyright information to the generated code. Is this possible currently?

I tried using javadoc()in JDefinedClass , it adds the information only above the class definition.

2

There are 2 answers

0
Raymond On BEST ANSWER

com.sun.codemodel.writer.PrologCodeWriter is exactly what you are looking for

0
Marco13 On

You can create a CodeWriter that writes the copyright header. This CodeWriter can delegate to another one - namely, to the one that you would usually pass to the CodeModel#build method.

A complete example:

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;
    }

}

The resulting class will be

// Copyright 2017 - example.com

package com.example;


public class Example {


}