2010-09-10 56 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在构造函数中是不可能的。静态工厂方法是唯一真正的方法(你甚至不能在字节码中作弊)。