Posted on 2008-09-08 17:01
G_G 阅读(2756)
评论(0) 编辑 收藏 所属分类:
javaGeneral
主页:http://code.google.com/apis/protocolbuffers/docs/overview.html
testProto.proto
package foo.bar;
option java_package = "com.proto";
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
运行命令
'/home/kaiyi/proto/bin/protoc' --java_out=src testProto.proto
使用( 本类可用,builder 可改,开用但 list 删除要使用比较郁闷的方法删除!)
package unit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.google.protobuf.InvalidProtocolBufferException;
import com.proto.TestProto;
import com.proto.TestProto.Person;
import com.proto.TestProto.Person.PhoneNumber;
public class Main {
public static void main(String[] args) throws InvalidProtocolBufferException {
//空创建
Person.Builder builder = Person.newBuilder();
builder.setName("liukaiyi");
builder.setId(1);
builder.setEmail("email");
PhoneNumber.Builder pBuilder1 = PhoneNumber.newBuilder();
pBuilder1.setNumber("1");
pBuilder1.setType(TestProto.Person.PhoneType.MOBILE);
PhoneNumber.Builder pBuilder2 = PhoneNumber.newBuilder();
pBuilder2.setNumber("2");
pBuilder2.setType(TestProto.Person.PhoneType.HOME);
builder.addPhone(pBuilder1);
builder.addPhone(pBuilder2);
//此处为存储到数据库 或 传输!
byte[] data = builder.build().toByteArray() ;
for(byte tb : data )
System.out.print( (char)tb );
//组建
Person person = Person.parseFrom(data);
Person.Builder builder2 = Person.newBuilder(person);
builder2.setEmail("test");
PhoneNumber.Builder pBuilder3 = PhoneNumber.newBuilder();
pBuilder3.setNumber("3");
pBuilder3.setType(TestProto.Person.PhoneType.HOME);
builder2.addPhone(pBuilder3);
//这 我最不明白的地方 , list 这 只能 使用 这种方法才可以删除 list ????
List list = new ArrayList(builder2.getPhoneList());
List<PhoneNumber> ltmp = builder2.getPhoneList() ;
for(int i=0;i<list.size();i++ ){
if(ltmp.get(i).getNumber().equals("2"))
list.remove( ltmp.get(i) ) ;
}
builder2.clearPhone().addAllPhone(list);
builder2.clearEmail();
System.out.println(list.size());
System.out.println();
byte[] data2 = builder2.build().toByteArray() ;
for(byte tb : data2 )
System.out.print( (char)tb );
}
}