Java:如何从HEAP获取对象?

时间:2015-11-24 15:42:14

标签: java unsafe

这是情景:

我在类中实例化了一个String,然后我在HEAP中获得了它的位置:

public class UnsafeExperiment {

    static String s = "ciao";

    public UnsafeExperiment() throws Exception {
        Unsafe unsafe = getUnsafeInstance();
        Field field = this.getClass().getDeclaredField("s");
        field.setAccessible(true);

        long position = unsafe.staticFieldOffset(field);
        wait();

    }

    private  Unsafe getUnsafeInstance() throws Exception {
        Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafeInstance.setAccessible(true);
        return (Unsafe) theUnsafeInstance.get(Unsafe.class);
    }
}

从另一个类,如何使用其地址调用HEAP中的String? (请,我对考虑使用这种方法的机会不感兴趣..我从图书馆了解到它是不安全的)

1 个答案:

答案 0 :(得分:0)

您可以按如下方式从position访问字符串:

String s = (String) unsafe.getObject(UnsafeExperiment.class, position);