java-protobuf

Google protocal buffer.

How to use

  1. Designing objects
  2. Describing objects

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    package tutorial;
    option java_package = "com.example.tutorial";
    option java_outer_classname = "AddressBookProtos";
    message Person {
    required string name = 1;
    required int32 id = 2;
    optional string email = 3;
    enum PhotoType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
    }
    message PhoneNumber {
    required string number = 1;
    optional PhotoType type = 2 [default = HOME];
    }
    required PhoneNumber phone = 4;
    }
    message AddressBook {
    repeated Person person = 1;
    }
  3. Compiling the description

  4. Obtaining the generated source-code
    $> protoc --java_out=$DST_DIR addressbook.proto
  5. Importing objects into your project
    Import package com.example.tutorial.
    Add protobuf-java-2.6.1.jar to build path.
  6. Instantiating objects

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    PhoneNumber number = PhoneNumber.newBuilder()
    .setNumber("12345678")
    .setType(PhotoType.MOBILE)
    .build();
    Person p = Person.newBuilder()
    .setName("tom")
    .setId(100)
    .setEmail("abc@hotmail.com")
    .addPhone(number)
    .build();
  7. Using objects

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // serialize.
    FileOutputStream fos1 = new FileOutputStream("TestSePB.dat");
    long start = System.nanoTime();
    p.writeTo(fos1);
    System.out.println("" + (System.nanoTime() - start));
    fos1.close();
    // deserialize.
    Person pp = Person.parseFrom(new FileInputStream("TestSePB.dat"));

Full code can be found on github