java如何打印出一个对象在内存中的地址呢?
下文笔者讲述输出对象内存中地址的方法分享,如下所示
使用getUnsafe()方法例:获取对象的内存地址
package com.reflection; import java.lang.reflect.Field; import sun.misc.Unsafe; public class test01 { static final Unsafe unsafe = getUnsafe(); static final boolean is64bit = true; // auto detect if possible. private static Unsafe getUnsafe() { try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); return (Unsafe) theUnsafe.get(null); } catch (Exception e) { throw new AssertionError(e); } } public static void printAddresses(String label, Object... objects) { System.out.print(label + ": 0x"); long last = 0; int offset = unsafe.arrayBaseOffset(objects.getClass()); int scale = unsafe.arrayIndexScale(objects.getClass()); switch (scale) { case 4: long factor = is64bit ? 8 : 1; final long i1 = (unsafe.getInt(objects, offset) & 0xFFFFFFFFL) * factor; System.out.print(Long.toHexString(i1)); last = i1; for (int i = 1; i < objects.length; i++) { final long i2 = (unsafe.getInt(objects, offset + i * 4) & 0xFFFFFFFFL) * factor; if (i2 > last) System.out.print(", +" + Long.toHexString(i2 - last)); else System.out.print(", -" + Long.toHexString(last - i2)); last = i2; } break; case 8: throw new AssertionError("Not supported"); } System.out.println(""); } public static void main(String[] args) throws ClassNotFoundException { User user1=new User(); User user2=new User(); int a=0; printAddresses("Address", a); printAddresses("Address", user1); printAddresses("Address", user2); } } class User { int id; String name; String school; @Override public String toString() { return "a{" + "id=" + id + ", name='" + name + '\'' + ", school='" + school + '\'' + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSchool() { return school; } public User() { } public void setSchool(String school) { this.school = school; } public User(int id, String name, String school) { this.id = id; this.name = name; this.school = school; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。