2010-09-10 53 views
2

我的系統既是jibx又是一個傳統的XML應用程序,我想構建一個構造函數,它可以接受一個xml字符串並將它解組到它自己的類中。像這樣:java構造函數分配整個類不只是字段

public ActiveBankTO(String xmlIn) 
    { 
     try 
     { 
      ByteArrayInputStream bin = new ByteArrayInputStream(xmlIn.getBytes()); 
      IBindingFactory bfact; 
      bfact = BindingDirectory.getFactory(ActiveBankTO.class); 
      IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); 
      this = (ActiveBankTO) uctx.unmarshalDocument(bin, null); 
     } catch (JiBXException e) 
     { 
      e.printStackTrace(); 
     } 
    } 

但顯然我不能分配「this」作爲變量。有沒有辦法做到這一點?我意識到我可以把它放到一個可以使用的靜態方法中,或者其他一些技巧使它可以工作,但是這已經出現在幾個不同形式的項目中,我想知道這個特定的方法是否可行。

回答

2

不,這是不可能的。靜態方法解決方案是最好的主意。

 
public static ActiveBankTO parseActiveBankTO(String xmlIn) { 
    ActiveBankTO newTO = null; 
    try { 
     ByteArrayInputStream bin = new ByteArrayInputStream(xmlIn.getBytes()); 
     IBindingFactory bfact; 
     bfact = BindingDirectory.getFactory(ActiveBankTO.class); 
     IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); 
     newTO = (ActiveBankTO) uctx.unmarshalDocument(bin, null); 
    } catch (JiBXException e) { 
     e.printStackTrace(); 
    } 
    return newTO; 
} 
+0

是的,這正是我最終選擇的方式。只是想我會問。 – scphantm 2010-09-12 15:43:03

1

編號ti在構造函數中是不可能的。靜態工廠方法是唯一真正的方法(你甚至不能在字節碼中作弊)。