I want to analyze the String object reference difference between heap reference and constant pool reference,using jmap to dump a java Program binary file,a Object address in bin
trying to use System.out.println
to get a real address ,and i can use it to find it binary form,but this method to println[Ljava.lang.String;@18b4aac2
,not a real address ,may like is virtual memory address.
so change method like is:
public class Main {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
String[] key = {"qwerty"};
String obj = "qwerty";
Unsafe unsafe = getUnsafe();
System.out.println(getAddressOf(key,unsafe));
System.out.println(getAddressOf(key[0],unsafe));
System.out.println(getAddressOf(args,unsafe));
System.out.println(getAddressOf(args[0],unsafe));
System.out.println(getAddressOf(obj,unsafe));
}
private static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
return (Unsafe) unsafeField.get(null);
}
private static <T> String getAddressOf(T object, Unsafe unsafe) throws NoSuchFieldException {
Object[] array = {object};
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 Long.toHexString(objectAddress);
}
}
but its still not right
how to get a real address or Why can't I get the true answer when using the methods mentioned above?