2

Proto3 has been simplified such that the required and optional fields are no longer supported (See Why required and optional is removed in Protocol Buffers 3). Is there still a way to label a certain field as required? I've looked into FieldOptions, and tried something like this:

message MyMeta {
  bool isRequired = 1;
}

extend google.protobuf.FieldOptions {
   MyMeta meta = 1234;
}

message Person {
  string name = 1 [ (meta) = { isRequired: true }];
  string address = 2  [ (meta) = { isRequired: true }];
  string remarks = 3;
}

After compiling it into Java code, and as I was checking the compiled Java code I don't see any link between the fields and its metadata I specified in proto. Did I miss something here?

Julius Delfino
  • 991
  • 10
  • 27

2 Answers2

3

After a bit of tinkering and using @Eric Anderson's idea on using proto reflection, here is a way to retrieve MyMeta from the Person.name field:

    Descriptor rootDesc = PersonProto.getDescriptor();
    FieldDescriptor name = rootDesc.findFieldByName("name");
    FieldDescriptor ext = rootDesc.getFile().getExtensions().get(0);
    MyMeta meta = (MyMeta) name.getOptions().getField(ext);
    boolean isReq = meta.getIsRequired();
Julius Delfino
  • 991
  • 10
  • 27
2

No, that functionality was removed; use documentation instead. If you are trying to use FieldOptions for your own extensions, then you can make your own protoc plugin to generate supplemental code (like a verify utility) or use proto reflection at runtime (via FooMessage.getDescriptor() and Descriptors.FieldDescriptor.getOptions() in Java).

Eric Anderson
  • 24,057
  • 5
  • 55
  • 76