Extending Protocol Buffers in Java
Asked Answered
L

1

7

I'm having trouble accessing extended protocol buffer members. Here is the scenario:

Message Foo {   optional int i = 1; }

message Bar {   extend Foo {
    optional int j = 10001;   } }

I don't have the Bar message within any of my other protos. How can I get Bar.j in Java? All examples I've found require a Bar within a message.

Thanks!

Latialatices answered 25/2, 2012 at 3:47 Comment(0)
P
8

Extensions in Protocol Buffer don't work necessarily as you would expect, i.e. they don't match the Java inheritance mechanism.

For your problem, I have created the following foobar.proto file:

package test;

message Foo {
    optional int32 i = 1;
    extensions 10 to 99999;
}

message Bar {
    extend Foo {
        optional int32 j = 10001;
    }
}

It creates Foobar.java, containing the classes Foobar.Bar and Foobar.Foo.

And here is a simple JUnit test case accessing Bar.j:

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import test.Foobar.Bar;
import test.Foobar.Foo;

public class TestFooBar {

    @Test
    public void testFooBar() {
        Foo foo = Foo.newBuilder().setI(123).setExtension(Bar.j, 456).build();
        assertEquals(Integer.valueOf(456), foo.getExtension(Bar.j));
    }
}

Hope that helps clarifying your problem!

Proximate answered 28/2, 2012 at 18:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.