Protocol buffer objects generated at runtime

后端 未结 2 1560
孤城傲影
孤城傲影 2020-12-28 19:46

a colleague of mine came with an idea of generating protocol buffers classes at runtime. Meaning:

  • There is C++ server application and Java client application c
2条回答
  •  不思量自难忘°
    2020-12-28 20:04

    For Java you may find following wrapper API ("protobuf-dynamic") easier to use than the original protobuf API:

    https://github.com/os72/protobuf-dynamic

    For example:

    // Create dynamic schema
    DynamicSchema.Builder schemaBuilder = DynamicSchema.newBuilder();
    schemaBuilder.setName("PersonSchemaDynamic.proto");
    
    MessageDefinition msgDef = MessageDefinition.newBuilder("Person") // message Person
        .addField("required", "int32", "id", 1)     // required int32 id = 1
        .addField("required", "string", "name", 2)  // required string name = 2
        .addField("optional", "string", "email", 3) // optional string email = 3
        .build();
    
    schemaBuilder.addMessageDefinition(msgDef);
    DynamicSchema schema = schemaBuilder.build();
    
    // Create dynamic message from schema
    DynamicMessage.Builder msgBuilder = schema.newMessageBuilder("Person");
    Descriptor msgDesc = msgBuilder.getDescriptorForType();
    DynamicMessage msg = msgBuilder
        .setField(msgDesc.findFieldByName("id"), 1)
        .setField(msgDesc.findFieldByName("name"), "Alan Turing")
        .setField(msgDesc.findFieldByName("email"), "at@sis.gov.uk")
        .build();
    

    Dynamic schemas can be useful in some applications to distribute changes without recompiling code (say in a more dynamically typed system). They can also be very useful for "dumb" applications that require no semantic understanding (say a data browser tool)

提交回复
热议问题