我想知道 JVM 分配给正在放置在系统内存中的对象的位置。
最佳答案
这可能是您不想做的事情。
如果您真的想要这样做,类似下面的代码可能会有所帮助:
package test;
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();
long address = addressOf(mine);
System.out.println("Addess: " + address);
//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();
}
}
但是
- 不能跨 JVM 甚至不同版本移植
- 由于 GC,对象可以随时移动,并且无法跨 GC 同步,因此结果可能没有意义
- 未在所有架构、字节序等方面进行测试。这可能无法在任何地方都使用
关于java - 如何在java中获取对象的内存位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7060215/