java构造函数来分配整个类,而不仅仅是字段
我的系统是jibx和一个遗留xml应用程序,我想构建一个构造函数,它可以接受xml字符串并将其解组到自己的类中。像这样:java构造函数来分配整个类,而不仅仅是字段,java,Java,我的系统是jibx和一个遗留xml应用程序,我想构建一个构造函数,它可以接受xml字符串并将其解组到自己的类中。像这样: public ActiveBankTO(String xmlIn) { try { ByteArrayInputStream bin = new ByteArrayInputStream(xmlIn.getBytes()); IBindingFactory bfact;
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”指定为变量。有没有办法让这一切顺利进行?我意识到我可以把它放在一个可以使用的静态方法中,或者用一些其他的技巧使它工作,但这是一些以各种形式出现在几个项目中的东西,我想知道这种特殊的方法是否可行。不,不可能。静态方法是最好的解决方案 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; } 公共静态ActiveBankTO解析ActiveBankTO(字符串xmlIn){ ActiveBankTO newTO=null; 试一试{ ByteArrayInputStream bin=新的ByteArrayInputStream(xmlIn.getBytes()); IBindingFactory bfact; bfact=BindingDirectory.getFactory(ActiveBankTO.class); IUnmarshallingContext uctx=bfact.createUnmarshallingContext(); newTO=(ActiveBankTO)uctx.unmarshalDocument(bin,null); }捕获(JiBXException e){ e、 printStackTrace(); } 返回纽托; }
不,在构造函数中不可能使用ti。静态工厂方法是唯一真实的方法(在字节码中甚至不能像这样作弊) 是的,这正是我最终的选择。我只是想问一下。