2015-11-24 39 views
0

这是情景:Java:如何从HEAP获取对象?

我已经实例化一个类的字符串,然后我已获得了其在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); 
    } 
} 

从另一个类,我怎么能叫使用堆中字符串它的地址? (请,我不感兴趣,在考虑有关机会使用这种方法。我从图书馆知道所涉及它是不安全的)

+0

为什么不只是传递一个字符串的引用?为什么你需要担心它在堆中的位置? –

+2

你为什么想这样做?像Java这样的托管语言的关键是不用担心这种情况 –

+0

这是一个用于反应性微服务系统框架的非常复杂场景的用例。 很长的事情做了简短: 我从一个REST接口DeferredResult,我需要在另一个应用程序中设置其结果:不幸的是,我不能传递DeferredResult作为参考,但作为序列化对象:所以如果我在其他应用程序中修改它原始DeferredResult的应用程序不会被修改。 对于这种动机,我需要从第二个应用程序将HEAP中的原始地址发送回第一个应用程序的观察者,其中DeferredResult是:当我拥有它时,我可以设置结果。 –

回答

0

您可以从它的position访问字符串如下:

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