// Msg.proto syntax = "proto3"; option java_package = "com.message.test"; message Person { string name = 1; int32 id = 2; string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { string number = 1; PhoneType type = 2; } repeated PhoneNumber phone = 4; message CountryInfo { string name = 1; string code = 2; int32 number = 3; } } message AddressBook { repeated Person person = 1; }
// protobuf compile 'com.google.protobuf:protobuf-java:3.6.0'
// Test.java
package com.message; import com.google.protobuf.InvalidProtocolBufferException; import com.message.test.Msg; import java.util.List; public class Test { public static void main(String[] args) { Msg.Person.Builder builder = Msg.Person.newBuilder(); builder.setEmail("minhowe@163.com"); builder.setId(1); builder.setName("apanda"); builder.addPhone(Msg.Person.PhoneNumber.newBuilder().setNumber("1001").setType(Msg.Person.PhoneType.MOBILE)); builder.addPhone(Msg.Person.PhoneNumber.newBuilder().setNumber("1002").setType(Msg.Person.PhoneType.HOME)); Msg.Person person = builder.build(); byte[] buf = person.toByteArray(); try{ Msg.Person person2 = Msg.Person.parseFrom(buf); System.out.println(person2.getName() + "," + person2.getEmail()); List<Msg.Person.PhoneNumber> listPhones = person2.getPhoneList(); for (Msg.Person.PhoneNumber photoNumber: listPhones) { System.out.println(photoNumber.getNumber()); } } catch (InvalidProtocolBufferException e) { e.printStackTrace(); } System.out.println(buf); } }