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

1

17

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?

Issacissachar answered 30/4, 2020 at 0:1 Comment(1)
Were you able to find a way to do this? Bumping into this same problem (We use lombox as well, but lombok generated annotation is skipped properly)Guttural
D
1

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")
                }
            }
        }
    }
}
Dionysiac answered 14/10, 2022 at 14:58 Comment(1)
This doesn't really answer the question, as the annotate_code option annotates with javax.annotation.Generated, but the question is specifically asking about a custom annotation. javax.annotation.Generated has source retention, which means tools that look at the .class files, like Jacoco, cannot see it. To make matters worse, the annotate_code option does not annotate nested classes.Dkl

© 2022 - 2024 — McMap. All rights reserved.