码迷,mamicode.com
首页 > 其他好文 > 详细

MessagePack的使用 - 直接传输自定义的对象

时间:2015-02-09 10:46:15      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

要直接使用自定义的对象进行传输,需要继承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 }

 

MessagePack的使用 - 直接传输自定义的对象

标签:

原文地址:http://www.cnblogs.com/IT-Monster/p/4280958.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!