1,创建unsafe工具类
public class UnsafeUtil {
public static Unsafe getUnsafe(){
try {
Field field= Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
return (Unsafe)field.get(null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static long getFieldOffset(Unsafe unsafe, Class obj, String field) {
try {
return unsafe.objectFieldOffset(obj.getDeclaredField(field));
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
2,测试
public static void main(String[] args) {
//测试是大端存储还是小端存储
Unsafe unsafe = UnsafeUtil.getUnsafe();
long a = unsafe.allocateMemory(8L);
unsafe.putLong(a,0x0102030405060708L);
byte b = unsafe.getByte(a);
ByteOrder byteOrder;
switch (b) {
case 0x01:
byteOrder = ByteOrder.BIG_ENDIAN;
break;
case 0x08:
byteOrder = ByteOrder.LITTLE_ENDIAN;
break;
default:
byteOrder = null;
}
System.out.println(byteOrder);
}