码迷,mamicode.com
首页 > 编程语言 > 详细

Protocol Buffer Java实例

时间:2015-03-06 18:59:34      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

大家要先下载protobuffer,在这里:

https://code.google.com/p/protobuf/downloads/list

注意,需要下载两个,一个是complier,另外一个是source code (我下载的是2.5的版本);

 

讲complier对应的 protoc.exe 拷贝至 source code 对应的./protobuf-2.5.0/src目录下(mvn 编译需要);

cd 到 ./protobuf-2.5.0/java 目录, 执行 mvn clean package 命令打包;

到target目录获取生成的protobuf-java-2.5.0.jar包(Java代码对protobuf依赖的jar包);

 

person.proto文件

package com.shine.pb;
option java_package = "com.shine.pb.person";
option java_outer_classname = "MyPerson";

message Person {
    required int32 id = 1;
    required string name = 2;
    optional string email = 3;

    enum PhoneType {
        MOBILE = 0;
        FIXED = 1;
    }
    
    message PhoneInfo {
        required string number = 1;
        required PhoneType type = 2 [default=MOBILE]; 
    }
    
    optional PhoneInfo phone = 4;
}

 

 

到protoc.exe所在目录,执行 protoc --java_out=./output/java ./messages/MyMessage.proto

可生成proto文件对应的Java类;

 

copy到自己eclipse对应src后;写main方法测试,代码如下:

package com.shine.pb.person;

import com.google.protobuf.InvalidProtocolBufferException;
import com.shine.pb.person.MyPerson.Person.PhoneType;


public class Test {
    
    public static void main(String[] args) throws InvalidProtocolBufferException {
        MyPerson.Person.Builder  builder = MyPerson.Person.newBuilder();
        builder.setId(1);
        builder.setName("shine");
        builder.setEmail("chenguodong@baidu.com");
        MyPerson.Person.PhoneInfo.Builder phoneInfoBuilder = MyPerson.Person.PhoneInfo.newBuilder();
        phoneInfoBuilder.setNumber("13899999999");
        phoneInfoBuilder.setType(PhoneType.MOBILE);
        builder.setPhone(phoneInfoBuilder.build());
        
        MyPerson.Person shine = builder.build();
        
        System.out.println(shine.getSerializedSize());
        System.out.println(shine.getEmail());
        System.out.println(shine.getName());
        System.out.println(shine.getPhone().getNumber());
        
        System.out.println("=============================================");
        
        byte[] data = shine.toByteArray();
        builder = MyPerson.Person.newBuilder();
        MyPerson.Person person = MyPerson.Person.parseFrom(data);
        System.out.println(person.getSerializedSize());
        System.out.println(person.getEmail());
        System.out.println(person.getName());
        System.out.println(person.getPhone().getNumber());
    }

}

 

Protocol Buffer Java实例

标签:

原文地址:http://www.cnblogs.com/shine_cn/p/4318980.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!