说明
io.netty.buffer.ByteBuf经常需要跟其它类型互相转化,例如ByteBuf类型作为Object类型函数参数传递,函数内部处理时将Object转换为ByteBuf。
代码示例
ByteBuf和Object类型互转
package com.thb;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
public class Demo {
public static void main(String[] args) {
// 创建一个ByteBuf
ByteBuf buf = Unpooled.buffer();
// 将ByteBuf变量赋值给对象变量
Object msg = buf;
System.out.println("msg == buf: " + (msg == buf));
if (msg instanceof ByteBuf) { // 如果msg是ByteBuf类型
// 将对象变量转化为ByteBuf变量
ByteBuf buf2 = (ByteBuf)msg;
System.out.println("buf2 == buf: " + (buf2 == buf));
System.out.println("buf2 == msg: " + (buf2 == msg));
System.out.println("buf.refCnt(): " + buf.refCnt());
buf2.release();
System.out.println("after call buf2 relase, buf.refCnt(): " + buf.refCnt());
}
}
}
运行输出:
msg == buf: true
buf2 == buf: true
buf2 == msg: true
buf.refCnt(): 1
after call buf2 relase, buf.refCnt(): 0