import sun.misc.Unsafe; import java.lang.reflect.Field; public class Main { private static final Unsafe unsafe; static { try { unsafe = getUnsafe(); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalStateException("Unsafe获取失败!", e); } } private static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); return (Unsafe) field.get(null); } @SafeVarargs public static <T> String objectAddress(T... objects) { long offset = unsafe.arrayBaseOffset(objects.getClass()); long factor = 8; final long i1 = (unsafe.getInt(objects, offset) & 0xFFFFFFFFL) * factor; return "0x" + Long.toHexString(i1); } public static void main(String[] args) { Object o = new Object(); System.out.println(o.hashCode()); System.out.println(o.hashCode()); System.out.println(objectAddress(o)); System.out.println(objectAddress(o)); byte[] ignored = new byte[10240]; System.gc(); System.out.println(objectAddress(o)); System.out.println(o.hashCode()); }
获取对象地址的方式
最新推荐文章于 2023-03-10 21:46:45 发布