Protostuff 运行时模式和多态性问题
Protostuff runtime schema and polymorphism issues
我在 Java 中有一个 类 的层次结构,我想使用 protostuff 对其进行序列化和反序列化。
类 如下(只是一个玩具示例)
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;
}
我使用以下代码使用运行时模式生成对对象进行序列化和反序列化,如下所示
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());
}
问题是这段代码的输出是
class Animal
class Animal
而不是
class Antelope
class Spider
如何在 serialization/deserialization 期间保留多态性信息?
希望有人能帮助我
我在 Java 中有一个 类 的层次结构,我想使用 protostuff 对其进行序列化和反序列化。
类 如下(只是一个玩具示例)
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;
}
我使用以下代码使用运行时模式生成对对象进行序列化和反序列化,如下所示
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());
}
问题是这段代码的输出是
class Animal
class Animal
而不是
class Antelope
class Spider
如何在 serialization/deserialization 期间保留多态性信息?
希望有人能帮助我