Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 799
Ivan Voroshilin Avatar asked Dec 09 '25 02:12

Ivan Voroshilin


1 Answers

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")
                }
            }
        }
    }
}
like image 103
Andrej Urvantsev Avatar answered Dec 11 '25 15:12

Andrej Urvantsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!