Protobuf Examples C++ and Java (2)

This sample .proto is taken from http://www.indelible.org/ink/protobuf-polymorphism/. Also see example 1

animal.proto


 package animal;

option java_outer_classname = "Animals";

message Cat
{
    optional bool declawed = 1;
}

message Dog
{
    optional uint32 bones_buried = 1;
}

message Animal
{
    required float weight = 1;
    optional Dog dog = 2;
    optional Cat cat = 3;
}

animal.cpp


#include 
#include "animal.pb.h"
using namespace std;
using namespace animal;

int main()
{
  Cat cat1;
  cat1.set_declawed(true);

  Animal animal;
  animal.set_weight(10.4);
  Cat* cat = animal.mutable_cat();

  cat->set_declawed(true);


  Dog *dog = animal.mutable_dog();
  dog->set_bones_buried (32);

  string s;
  animal.SerializeToString(&s);

  Animal animal2;

  animal2.ParseFromString(s);

  printf("weight %f\n", animal2.weight());

  if (animal.has_cat())
  {
    printf("cat %d\n", animal.cat().declawed());
  }

  if (animal.has_dog())
  {
    printf("dog %d\n", animal.dog().bones_buried());
  }

  return 0;
} 

animal.java


import animal.Animals;
import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.*;
import java.io.IOException;

 
class AnimalExample {

 
    public static void main(String[] args) throws Exception {

        Animals.Animal animal =  Animals.Animal.newBuilder().
            setWeight(10.4F)
            .setDog(Animals.Dog.newBuilder().setBonesBuried(32).build())
            .setCat(Animals.Cat.newBuilder().setDeclawed(true).build())
            .build();
        
        

        byte[] data = animal.toByteArray();

        Animals.Animal animal2 = Animals.Animal.newBuilder().mergeFrom(data).build();
        
        System.out.println("Animal weight " + animal2.getWeight());

        if (animal2.hasCat()) {

            System.out.println("Cat " + animal2.getCat().getDeclawed());
        }

        if (animal2.hasDog()){
            System.out.println("Dog " + animal2.getDog().getBonesBuried());
        }
    }
    
}