How do I get protobuf methods to resolve in intellij when using bazel?

Viewed 1516

I'm having an issue where I have a working java program that uses protobuf and is built using bazel, but where intellij doesn't recognize the method toByteArray. I forked https://github.com/cgrushko/proto_library on my local machine, imported the workspace into intellij and built. I then added the following java main class:

package src;

import demo.PersonOuterClass;

public class Main {
    public static void main(String argv[]) {
    byte[] ba = PersonOuterClass.Person.newBuilder().setEmail("dwwd").build().toByteArray();
    for (byte b : ba) {
      System.out.println(b);
    }
  }
}

and the following bazel build rule

java_binary(
    name = "Main",
    main_class = "src.Main",
    srcs = ["Main.java"],
    deps = [":person_java_proto"]
)

The program builds and runs properly, but in intellij toByteArray() is red and intellij says that it can't resolve the method.

I suspect the issue is that generated Person extends com.google.protobuf.GeneratedMessageV3 but intellij doesn't know about GeneratedMessageV3 and that it extends a class, AbstractMessageLite, that defines the toByteArray method.

Anyone know how to fix either the bazel build target(s) or intellij so that toByteArray is resolved by the ide?

Thanks,

Tom.

2 Answers

I solved this problem by marking bazel-/external/java/com_google_protobuf_java/core/src/main/java as a source root. (Right click -> Mark Directory as -> Sources Root)

I fixed this on my Bazel project by adding com.google.protobuf:protobuf-java as a dependency for the Bazel library depending on protobuf.

Related