Search code examples
javaannotationsprotocol-buffersjacocogenerated

How to add Java compile-time Custom annotation to Protobuf generated code


I use gRPC framework with Proto 3. We have a java code coverage tool Jacoco which scans java byte code for java "annotation" @Generated in compiled classes and if it has one, it skips that java class from coverage. But Proto-compiler adds this annotation:

@javax.annotation.Generated(
    value = "by gRPC proto compiler (version 1.20.0)",
    comments = "Source: myProto.proto")
public class MyClass {
...
}

But the annotation javax.annotation.Generated has @Retention(value=SOURCE) which doesn't exist in compiled classes.

Is there a way to add annotation to java generated files from protobuf as compile-time?


Solution

  • That's an old question, but still

    https://github.com/protocolbuffers/protobuf/issues/42

    So you suppose to add --java_out=annotate_code to the list of protoc options.

    If you use https://github.com/google/protobuf-gradle-plugin gradle plugin for code generation, then you can do like this(Gradle Kotlin DSL):

    protobuf {
        generateProtoTasks {
            all().forEach { task ->
                task.builtins {
                    getByName("java") {
                        option("annotate_code")
                    }
                }
            }
        }
    }