Proto Generated类的toString导致异常

时间:2015-12-29 07:21:19

标签: java junit protocol-buffers protoc

我正在按照Google的教程[https://developers.google.com/protocol-buffers/docs/javatutorial?hl=en]编写一个Proto类。

我的Proto文件是

package protoc_Shashi;

option java_package="com.shashi.protoc.generated";
option java_outer_classname="AddressBookProtos";

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 number = 4;
}

message AddressBook {
    repeated Person person = 1;
}

我正在编写一个junit测试用例来创建一个新的Person对象,如教程中所指定的 创建了对象,但是调用它的toString()方法给出了一个错误,它应该被子类覆盖。 Stacetrace同样如下

java.lang.UnsupportedOperationException: This is supposed to be overridden by subclasses.
    at com.google.protobuf.GeneratedMessage.getUnknownFields(GeneratedMessage.java:192)
    at com.google.protobuf.TextFormat$Printer.print(TextFormat.java:301)
    at com.google.protobuf.TextFormat$Printer.printFieldValue(TextFormat.java:434)
    at com.google.protobuf.TextFormat$Printer.printSingleField(TextFormat.java:353)
    at com.google.protobuf.TextFormat$Printer.printField(TextFormat.java:309)
    at com.google.protobuf.TextFormat$Printer.print(TextFormat.java:299)
    at com.google.protobuf.TextFormat$Printer.access$400(TextFormat.java:273)
    at com.google.protobuf.TextFormat.print(TextFormat.java:76)
    at com.google.protobuf.TextFormat.printToString(TextFormat.java:143)
    at com.google.protobuf.AbstractMessage.toString(AbstractMessage.java:79)
    at com.shashi.protoc.generated.AddressBookProtosTest.createPerson(AddressBookProtosTest.java:29)

我的junit测试类如下

package com.shashi.protoc.generated;

import org.junit.Test;

/**
 * @author Shashi Bhushan
 *         Created on 29/12/15.
 *         For Google-Protoc
 */
public class AddressBookProtosTest {

    @Test
    public void createPerson(){
        AddressBookProtos.Person person =
                AddressBookProtos.Person.newBuilder()
                .setId(100)
                .setName("Shashi")
                .setEmail("sb@sb.com")
                .addNumber(
                        AddressBookProtos.Person.PhoneNumber.newBuilder()
                                .setNumber("555")
                                .setType(AddressBookProtos.Person.PhoneType.WORK)
                )
                .build();

        System.out.println("Is Initialized : " +
                person.isInitialized());
        System.out.println("To String : " +
                person.toString());     // Error on this line
    }
}

我在这里错过了一些小事吗?

1 个答案:

答案 0 :(得分:3)

确保您的protoclibprotobuf.jar版本完全相同。从您给出的堆栈跟踪中,我的猜测是您正在使用protoc v3和libprotobuf.jar v2.x,尽管我不确定。通常,您始终必须使用完全相同的这两个版本,因为protoc生成的代码依赖于libprotobuf.jar中的私有API,这些API通常会在不同版本之间发生变化。