实现说明
主要控制逻辑均整合于该自定义类中 PacketIntViews和函数 main中。
使用要点
- 复制、运行:标准库能接住文件里的每一个调用。
- 每一步打印都带着自己的标签:
raw slice:、as big-endian: 0x、as little-endian: 0x。
常见问题
运行「VarHandle 字节数组视图按字节序读写」会打印什么?
运行文件本身,raw slice:、as big-endian: 0x、as little-endian: 0x 这些前缀各对应一段演示逻辑。
核心语句
VarHandle littleInt = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.LITTLE_ENDIAN);
VarHandle bigInt = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.BIG_ENDIAN);
boolean swapped = bigInt.compareAndSet(packet, 0, 42, 99);
代码示例
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
import java.util.HexFormat;
public class PacketIntViews {
public static void main(String[] args) {
VarHandle bigInt = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.BIG_ENDIAN);
VarHandle littleInt = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.LITTLE_ENDIAN);
byte[] packet = new byte[12];
// Plain get/set accepts any in-bounds byte offset, even unaligned offsets like 2
bigInt.set(packet, 2, 0x01020304);
System.out.println("raw slice: " + HexFormat.of().formatHex(packet, 2, 6));
System.out.println("as big-endian: 0x" + Integer.toHexString((int) bigInt.get(packet, 2)));
System.out.println("as little-endian: 0x" + Integer.toHexString((int) littleInt.get(packet, 2)));
// Aligned offset 0 supports volatile/CAS modes directly on byte[]
bigInt.setVolatile(packet, 0, 42);
boolean swapped = bigInt.compareAndSet(packet, 0, 42, 99);
System.out.println("aligned cas ok: " + swapped + ", header=" + (int) bigInt.getVolatile(packet, 0));
// Atomic CAS at unaligned byte offset throws IllegalStateException
try {
bigInt.compareAndSet(packet, 2, 0x01020304, 0);
} catch (IllegalStateException ex) {
System.out.println("unaligned cas rejected: " + ex.getClass().getSimpleName());
}
}
}