2010-02-05 40 views
2

我正在開發支持對象聚合傳輸的CORBA類對象協議。Java中的延遲參考設置

當聚合對象序列化時,它們可能會引用稍後序列化的objets。這些是前瞻性參考。一個簡單的例子是一個圓形列表。如果每個對象都有對先前序列化對象的引用,則第一個對象將引用最後一個序列化對象來關閉該循環。

當反序列化和實例化一個包含這樣的前向引用的對象時,它的值是未知的。只有當對應的對象被反序列化和實例化時,參考值已知並且可以被設置。

在C或C++中,我使用引用(指針)本身來保存對實例化時設置的同一對象的引用列表。在Java中這是不可能的。

我該如何在Java中實現這樣的延遲參考設置?

回答

1

如果對象是不可改變的,那麼你建立一個臨時的結構將在適當的順序(顯然,這並不適用於圓名單,除非你使用的設置最終場反射序列化支持)創建它們。

如果不是,請稍後在外部列表中記錄所需的操作,或者爲每個成員使用具有解析方法的接口: public interface IBar IBar resolve();

static IBar EMPTY = new IBar() { 
     public IBar resolve() { 
      throw new RuntimeException(); 
     } 
    } 
} 

public interface IFoo { 
    IFoo resolve (); 
    ... 
} 

public class Foo implements IFoo { 
    private IBar bar = IBar.EMPTY; 

    public Foo (IBar bar) { this.bar = bar; } 

    public Bar getBar() { 
     return bar.resolve(); 
    } 

    public String getId() { ... } 

    public IFoo resolve() { 
     bar = bar.resolve(); 
     return this; 
    } 
} 

public class Loader { 
    private HashMap<String,IFoo> fooRefs = new ... 
    private HashMap<String,IBar> barRefs = new ... 

    private IBar barRef (String id) { 
     IFoo foo = fooRefs.get(id); 

     if (foo==null) { 
      foo = new ForwardFooRef(id); 
      fooRefs.put(id,foo); 
     } 

     return foo; 
    } 

    private IFoo created (IFoo foo) { 
     IFoo extant = fooRefs.get(foo.getId()); 

     if (extant != null) 
      if (extant instanceof ForwardFooRef) 
       ((ForwardFooRef)extant).setReferent(foo); 
      else 
       throw new RuntimeException("more than one object with the same id "); 

     return foo; 
    } 

    public void load() { 
     create each object 
     register it using created 
     if a ref is found, use the maps to look it up 
     if the ref is in teh map, use it 
     if ref is forward, it's created with a temp 

     walk object tree resolving anything 
+0

您的示例很有趣,因爲它使用技巧來存儲對保留解析前向引用所需信息的虛擬對象的引用。這個虛擬對象也可以容納侵入鏈。 在我的系統中,所有可序列化的類繼承自基類Serializable,它可以有一個方法來解析前向引用。該實現可以遍歷所有引用,如果它們引用一個虛擬Serializable對象,則使用其包含的信息來解析該鏈接。 是這個想法嗎?無論如何,這是非常好的。 – chmike 2010-02-05 15:08:49