1

Unsafe功能之2: 对象属性值增改查


1. 对象属性值set

1.1 set 直接内存地址数据

设置直接内存地址上的指定类型的数据-address

public native void    putByte(long address, byte x);
// 省略....Short/Int/Char/Float/Long/Double/Boolean/Object](address, x)

1.2 set 指定对象偏移地址数据

设置指定对象偏移地址上的指定类型的数据-(o, offset, x)

public native void    putByte(Object o, long offset, byte x);
public native void    putByteVolatile(Object o, long offset, byte x);
// 省略....put[Short/Int/Char/Float/Long/Double/Boolean/Object](Object o, long offset, x)
// 省略....put[Short/Int/Char/Float/Long/Double/Boolean/Object]Volatile(Object o, long offset, x)

2. 对象属性值 get

2.1 get指定内存地址数据(address)

获取指定内存地址上的指定类型的数据(address):

`allocateMemory(long bytes)`是分配了 bytes 个字节的内存空间;下面的get方法是 直接内存地址 `address` 上获取对应类型数据. 比如: getByte(address) 从内存 address取一个Byte类型的值;
public native byte    getByte(long address);
public native short   getShort(long address);
public native int     getInt(long address);
public native char    getChar(long address);
public native long    getLong(long address);
public native float   getFloat(long address);
public native double  getDouble(long address);

2.2 get 指定对象偏移地址数据

获取指定对象偏移地址上的指定类型的数据(Object o, long offset)

public native byte    getByte(Object o, long offset);
public native byte    getByteVolatile(Object o, long offset);
public native short   getShort(Object o, long offset);
public native short   getShortVolatile(Object o, long offset);
public native int     getInt(Object o, long offset);
public native int     getIntVolatile(Object o, long offset);
public native char    getChar(Object o, long offset);
public native char    getCharVolatile(Object o, long offset);
public native float   getFloat(Object o, long offset);
public native float   getFloatVolatile(Object o, long offset);
public native long    getLong(Object o, long offset);
public native long    getLongVolatile(Object o, long offset);
public native double  getDouble(Object o, long offset);
public native double  getDoubleVolatile(Object o, long offset);
public native boolean getBoolean(Object o, long offset);
public native boolean getBooleanVolatile(Object o, long offset);
// Object对象
public native Object getObject(Object o, long offset);
public native Object getObjectVolatile(Object o, long offset);

3. 对象属性值 update :

直接通过内存地址, 操作指定对象的属性

3.1 getAndAddInt

在指定对象或数组o上, 对偏移量 offset处的属性的值v进行操作, 增加的量为delta`

public final int getAndAddInt(Object o, long offset, int delta){...}

3.2 getAndAddLong

同上, offset所在字段的值为long

public final long getAndAddLong(Object o, long offset, long delta)

3.3 getAndSetLong

替换对象o的偏移量 offset处的 值, 不论旧的值是多少, 改为新的值 newValue

public final int getAndSetInt(Object o, long offset, int newValue)

3.4 getAndSetLong

同上, 修改的类型为long

public final long getAndSetLong(Object o, long offset, long newValue)

3.5 getAndSetObject

同上, 修改类型为引用对象

public final Object getAndSetObject(Object o, long offset, Object newValue)

丰木
322 声望19 粉丝

遇见超乎想象的自己!