获取java对象地址的一个工具类
By:Roy.LiuLast updated:2019-10-25
一个获取java对象地址的工具类:
import java.lang.reflect.Field; import sun.misc.Unsafe; public class Addresser { private static Unsafe unsafe; static { try { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); unsafe = (Unsafe)field.get(null); } catch (Exception e) { e.printStackTrace(); } } public static long addressOf(Object o) throws Exception { Object[] array = new Object[] {o}; long baseOffset = unsafe.arrayBaseOffset(Object[].class); int addressSize = unsafe.addressSize(); long objectAddress; switch (addressSize) { case 4: objectAddress = unsafe.getInt(array, baseOffset); break; case 8: objectAddress = unsafe.getLong(array, baseOffset); break; default: throw new Error("unsupported address size: " + addressSize); } return(objectAddress); } public static void main(String... args) throws Exception { Object mine = "Hi there".toCharArray(); Object another = "Hi there".toCharArray(); long address = addressOf(mine); long addressAnother = addressOf(another); Object mine2 = mine; long addressMine2 = addressOf(mine); System.out.println("mine Addess: " + address); System.out.println("mine2 Addess: " + addressMine2); System.out.println("another Addess: " + addressAnother); //Verify address works - should see the characters in the array in the output printBytes(address, 27); } public static void printBytes(long objectAddress, int num) { for (long i = 0; i < num; i++) { int cur = unsafe.getByte(objectAddress + i); System.out.print((char)cur); } System.out.println(); } }
From:一号门
Previous:收藏一个java操作HDFS的工具类,比较简单
Next:yybi.com在易名拍卖,在此做个广告
COMMENTS