public class UnsafeTest {
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public static void main(String[] args) throws NoSuchFieldException {
UnsafeTest unsafeTest = new UnsafeTest();
Unsafe unsafe = null;
try {
Class<Unsafe> unsafeClass = Unsafe.class;
Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = (Unsafe) theUnsafe.get(unsafeClass);
}catch (Exception e) {
}
long offset = unsafe.objectFieldOffset(UnsafeTest.class.getDeclaredField("i"));
unsafe.putInt(unsafeTest, offset, 2);
System.out.println(unsafeTest.getI());
}
}
注:反射实例代码参考博文:https://blog.csdn.net/iteye_10121/article/details/82553203
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。