import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import sun.misc.Unsafe;
import java.util.Collections;
import java.lang.reflect.Field;
public static void main(String[] args) {
String a = new String("123"); String b = new String("123");
System.out.println(getAddresses(a));
System.out.println(getAddresses(b));
}
public static String getAddresses(Object... objects)
{
StringBuffer sb = new StringBuffer();
sb.append("0x");
// sun.arch.data.model=32 // 32 bit JVM
// sun.arch.data.model=64 // 64 bit JVM
boolean is64bit = Integer.parseInt(System.getProperty("sun.arch.data.model")) == 32 ? false : true;
Unsafe unsafe = getUnsafe();
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;
// 输出指针地址
sb.append(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)
sb.append(", +" + Long.toHexString(i2 - last));
else
sb.append(", -" + Long.toHexString(last - i2));
last = i2;
}
break;
case 8:
throw new AssertionError("Not supported");
}
return sb.toString();
}
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);
}
}
java打印出内存地址 java 输出对象内存地址
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
承前启后,Java对象内存布局和对象头JVM Java
-
java循环创建对象内存溢出怎么解决
本文简要介绍了Java循环创建对象内存溢出如何解决。
java 内存溢出 对象引用 -
Java中打印对象内存地址
java是获取不到对象的地址的,但是你可以获取hashcode,对象的hashcode在某种意义上就相当于对象的地址了,hashCode
对象内存地址 Java中打印对象内存地址 Java打印对象内存地址 Java获取对象内存 Java获取对象内存地址