问题
定义了一个接口,返回值为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
代码在Hessian2Input
的readObject
方法:
/** * 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