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

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

 

转载于:https://www.cnblogs.com/IT-Monster/p/4280958.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值