当前,我有一个工厂方法可以从XML创建RndObj
public static RndObj loadRndObjFromXMLFile(String xmlFile) {
RndObj ro = null;
try {
JAXBContext context = JAXBContext.newInstance(RndObj.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
File file = new File(xmlFile);
ro = (RndObj) unmarshaller.unmarshal(file);
} catch (JAXBException e) {
}
但是我更希望在RndObj中只有这样的构造函数
public RndObj(String xmlFile) {
//this = Factory.loadRndObjFromXMLFile(xmlFile);--------- would be nice
RndObj ro = Factory.loadRndObjFromXMLFile(xmlFile);
this.attribute1 = ma.getAttribute1();
this.attribute2 = ma.getAttribute2();
this.attribute3 = ma.getAttribute3();
this.attribute4 = ma.getAttribute4();
this.attribute5 = ma.getAttribute5();
this.attribute6 = ma.getAttribute6();
}
它有效,但:我需要复制大量的属性和字段,这有点糟,我创建了两个对象,然后从一个对象复制到另一个对象。另外,有时可能会有一个新字段,我总是必须跟踪此构造函数是up2date。
是否有更好的方法来实现我正在尝试的目标?
取决于您的限制和数据类的复杂性。
一个简单的选择是不使用构造函数,而是使用静态方法。类似于:
public class RndObj{
// other stuff
static RndObj load(String xmlFile){
return Factory.loadRndObjFromXMLFile(xmlFile);
}
}
另一个选择是库BeanUtils:
public RndObj(String xmlFile) {
//this = Factory.loadRndObjFromXMLFile(xmlFile);--------- would be nice
RndObj ro = Factory.loadRndObjFromXMLFile(xmlFile);
BeanUtils.copyProperties(ro, this);
}
不太适合在构造函数中泄漏this
。如果这些类只是一个数据容器,那应该没问题。