1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| package com.example.protostuff;
import io.protostuff.LinkedBuffer; import io.protostuff.ProtostuffIOUtil; import io.protostuff.runtime.RuntimeSchema;
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List;
public class ProtostuffDemo { public static void main(String[] args) throws Exception { List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); Person person = new Person(1, "111", list); RuntimeSchema<Person> schema = RuntimeSchema.createFrom(Person.class);
byte[] bytes = ProtostuffIOUtil.toByteArray(person, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE)); System.out.println(bytes.length); Person dePerson1 = schema.newMessage(); ProtostuffIOUtil.mergeFrom(bytes, dePerson1, schema); System.out.println(dePerson1.toString());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ProtostuffIOUtil.writeDelimitedTo(byteArrayOutputStream, person, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE)); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); Person dePerson2 = schema.newMessage(); ProtostuffIOUtil.mergeDelimitedFrom(byteArrayInputStream, dePerson2, schema); System.out.println(dePerson2); } }
class Person { int age; List<String> more; private String name;
public Person() { }
public Person(int age, String name, List<String> more) { this.age = age; this.name = name; this.more = more; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public List<String> getMore() { return more; }
public void setMore(List<String> more) { this.more = more; }
@Override public String toString() { return "Person{" + "age=" + age + ", name='" + name + '\'' + ", more=" + more + '}'; } }
|