Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

java - error with serialization with protobuf

I'm trying to serialize a structure with protobuf. after many hours trying to figure out what I'm doing wrong I decided to test the google's example and it didn't worked as well

I have the following protocol from google (https://developers.google.com/protocol-buffers/docs/javatutorial):

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;
    repeated PhoneNumber phone = 4;

    enum PhoneType {
        MOBILE = 0;
        HOME = 1;
        WORK = 2;
    }

    message PhoneNumber {
        required string number = 1;
        optional PhoneType type = 2 [default = HOME];
    }
}

message AddressBook {
    repeated Person person = 1;
}

and I'm trying to serialize it with:

Person john = Person.newBuilder()   
    .setId(1234)
    .setName("John Doe")
    .setEmail("jdoe@example.com")
    .addPhone(
        Person.PhoneNumber.newBuilder()
            .setNumber("555-4321")
            .setType(Person.PhoneType.HOME))
    .build();

byte[] serialized = john.toByteArray();

and I get "java.lang.UnsupportedOperationException: This is supposed to be overridden by subclasses."

Thanks;

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Marc said, A mismatch in Protocol Buffer versions will give you this exact message. In particular if

  • The .proto definition is converted to java using the 2.4.3 (or earlier) protoc.exe
  • You use the 2.5.0 protobuffers library

you will get this message in many methods (e.g. getParserForType, getUnknownFields) of class GeneratedMessage. There are no doubt other potential mismatch's that will cause this error


With protocol buffers 2.5.0 it is essential you regenerate all java classes with the 2.5.0 version of protoc (or on windows protoc.exe).


If you do the reverse - run code generated by protoc version 2.5 with the libraries for protocol buffers version 2.4. You will get the following message

java.lang.VerifyError: class xxx.xxx.xx.. 
overrides final method getUnknownFields.()Lcom/google/protobuf/UnknownFieldSet;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...