Protostuff runtime schema and polymorphism

71 views
Skip to first unread message

slux83

unread,
Feb 6, 2019, 12:28:35 PM2/6/19
to protostuff
Hi,

I have a hierarchy of classes in Java that I want to serialize and deserialize using protostuff.


The classes are the following (just a toy example)

class Wrapper {
   
public List<Being> beings;
}

class Being {
   
public Animal animal;
}

class Animal {
   
public String sex;
   
public int legs;
}

class Antelope extends Animal {
   
public int speed;
   
public String furType;
}

class Spider extends Animal {
   
public int numberOfEyes;
   
public int size;
}


I'm using the following code to serialize and deserialize the objects using runtime schema generation as the following

public static void main(String[] args) {
   
LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);

   
Being b1 = new Being();
   
Antelope a1 = new Antelope();
    a1
.legs = 4;
    a1
.furType = "Fuzzy";
    a1
.sex = "M";
    a1
.speed = 70;
    b1
.animal = a1;

   
Being b2 = new Being();
   
Spider s1 = new Spider();
    s1
.legs = 4;
    s1
.sex = "M";
    s1
.numberOfEyes = 8;
    s1
.size = 2;
    b2
.animal = s1;

   
Wrapper w = new Wrapper();
    w
.beings = new ArrayList<>();
    w
.beings.add(b1);
    w
.beings.add(b2);

   
// Serialize
   
Schema<Wrapper> schema = RuntimeSchema.getSchema(Wrapper.class);
   
byte[] data = ProtostuffIOUtil.toByteArray(w, schema, buffer);

   
// Deserialize
   
Wrapper w1 = schema.newMessage();
   
ProtostuffIOUtil.mergeFrom(data, w1, schema);

   
System.out.println(w1.beings.get(0).animal.getClass());
   
System.out.println(w1.beings.get(1).animal.getClass());
}


This code produces 

class Animal
class Animal



So it seems the information about the real sub-class is lost somewhere.

How can I do to preserve the sub-class information?

I'd like to have as output


class Antelope
class Spider


Thanks

David Yu

unread,
Feb 6, 2019, 12:29:43 PM2/6/19
to protostuff
If your object heirarchy involves a concrete class subclassing another concrete class (not using abstract classes), set: -Dprotostuff.runtime.morph_non_final_pojos=true

--
You received this message because you are subscribed to the Google Groups "protostuff" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protostuff+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


--
When the cat is away, the mouse is alone.
dyuproject.com

David Yu

unread,
Feb 6, 2019, 12:30:32 PM2/6/19
to protostuff

slux83

unread,
Feb 7, 2019, 3:15:49 AM2/7/19
to protostuff
Many thanks! It worked!
Reply all
Reply to author
Forward
0 new messages