java.lang.IndexOutOfBoundsException - 使用协议缓冲区构建

我正在使用 Protobuff 构建我的 Java 对象,为什么java.lang.IndexOutOfBoundsException: Index: 0, Size: 0在调用setHeader(0, h1)我的代码时总是收到异常。


这是我的代码:


        Person.Header h1 = Person.Header.newBuilder()

                .setKey("Key1")

                .setValue("value1")

                .build();


        Person person = Person.newBuilder()

                .setBody("TestBody")

                .setHeader(0, h1)

                .build();

这是我的 protobuff 消息(调用 dataformat.proto):


syntax = "proto3";

package tutorial;


option java_package = "tutorial";


message Person {

    string body = 1;

    repeated Header header = 2;


    message Header {

        string key = 3;

        string value = 4;

    }

}

堆栈跟踪:


java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

    at java.util.ArrayList.set(ArrayList.java:453)

    at com.google.protobuf.ProtobufArrayList.set(ProtobufArrayList.java:96)

    at tutorial.Dataformat$Person.setHeader(Dataformat.java:572)

    at tutorial.Dataformat$Person.access$1200(Dataformat.java:42)

    at tutorial.Dataformat$Person$Builder.setHeader(Dataformat.java:815)


慕容708150
浏览 97回答 1
1回答

肥皂起泡泡

setHeader()期望索引已经存在;它不会增加列表大小。这与java.util.List. 你可以addHeader()改用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java