说明
通过io.netty.buffer.ByteBuf的asReadOnly()函数,可以返回一个只读的ByteBuf;通过isReadOnly()函数,可以判断该ByteBuf是否是只读的。
示例
package com.thb;import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;public class Test {public static void main(String[] args) {// 创建一个ByteBufByteBuf buf = Unpooled.buffer();buf.writeByte(0x68);System.out.println("buf.isReadOnly: " + buf.isReadOnly());// 返回一个readOnly ByteBufByteBuf readOnlyBuf = buf.asReadOnly();// 判断readOnlyBuf和buf是否是同一个,返回falseSystem.out.println("buf == readOnlyBuf: " + (buf == readOnlyBuf));System.out.println("readOnlyBuf.isReadOnly: " + readOnlyBuf.isReadOnly());System.out.println("readOnlyBuf.readerIndex: " + readOnlyBuf.readerIndex());System.out.println("readOnlyBuf.writerIndex: " + readOnlyBuf.writerIndex());//readOnlyBuf.writeByte(0x16); // 如果向readOnly ByteBuf中写入会抛出异常}
}
运行输出:
buf.isReadOnly: false
buf == readOnlyBuf: false
readOnlyBuf.isReadOnly: true
readOnlyBuf.readerIndex: 0
readOnlyBuf.writerIndex: 1