要直接使用自定义的对象进行传输,需要继承AbstractTemplate该类
自定义的对象,一定要有@Message注解,负责会报错:
@Message public class TestObj { private int age; private String name; private long phone; private double score; public TestObj() { // TODO Auto-generated constructor stub } public TestObj(int age,String name,long phone,double score) { this.age = age; this.name = name; this.phone = phone; this.score = score; } 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 long getPhone() { return phone; } public void setPhone(long phone) { this.phone = phone; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } }
该对象对应的template类
1 public class TestTemplate extends AbstractTemplate<TestObj> { 2 3 4 @Override 5 public void write(Packer pk, TestObj target, boolean required) 6 throws IOException { 7 if(target == null) 8 { 9 if(required) 10 { 11 throw new MessageTypeException("Attempted to write null"); 12 } else 13 { 14 pk.writeNil(); 15 return; 16 } 17 } else 18 { 19 pk.write(target); 20 return; 21 } 22 } 23 24 @Override 25 public TestObj read(Unpacker u, TestObj target, boolean required) 26 throws IOException { 27 28 if(!required && u.trySkipNil()) 29 return null; 30 else 31 return u.read(TestObj.class); 32 } 33 34 public static TestTemplate getInstance() 35 { 36 return instance; 37 } 38 39 40 static final TestTemplate instance = new TestTemplate(); 41 42 }
时间: 2024-10-06 06:55:53