Dubbo Hessian2序列化问题

博客分析了Dubbo中Hessian2序列化导致的类型转换异常问题。当接口返回Byte类型时,consumer在反序列化过程中遇到了Integer转Byte的异常。通过查看Hessian2的源码,确认了问题源于Hessian2将byte序列化为Integer。解决方案包括更换序列化协议或在接收端将Object转换为Byte。
摘要由CSDN通过智能技术生成
                       

问题

定义了一个接口,返回值为Map<String, Byte>,consumer收到结果后,使用Byte value = map.get(key)获取结果,抛出了如下类型转换异常:
如下:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Byte    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)    at java.lang.reflect.Method.invoke(Method.java:498)
  
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

当时很奇怪,为什么返回值已经是Map<String, Byte>了,还会抛类型转换异常呢。

分析

首先想到的是通过debug确认返回的类型是否是Byte,设置断点后发现返回的Map的value的类型并不是Byte而是Integer,那么为什么会是Integer呢?
这里猜测这里很可能是dubbo序列化导致的,dubbo默认使用Hessaian2作为序列化协议,所以去看了下Hessian2的序列化实现,果不其然,byte会被反序列化成Integer

代码在Hessian2InputreadObject方法:

/**   * Reads an arbitrary object from the input stream when the type   * is unknown.   */  public Object readObject()    throws IOException  {    int tag = _offset < _length ? (_buffer[_offset++] & 0xff) : read();    switch (tag) {    case 'N':      return null;    case 'T':      return Boolean.valueOf(true);    case 'F':      return Boolean.valueOf(false);      // direct integer    case 0x80: case 0x81: case 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值