[英]JAXB: copy only required properties to the object
我有一个带有JAXB注释的类。 该类的强制属性具有注释@XmlElement(required = true)。 有没有办法将类的对象复制到同一个类的另一个对象,以便只复制所需的属性,并且可选的属性为空?
谢谢,
更新:我认为我需要澄清我正在寻找一个通用的解决方案,即不需要事先了解类和属性的解决方案。
copy()方法的一个示例:
class YourJaxbClass {
@XmlElement(required = true)
private String property1;
@XmlElement //this one is not required
private String property2;
public YourJaxbClass copy(){
YourJaxbClass copy = new YourJaxbClass();
//only copy the required values:
copy.property1 = this.property1;
return copy;
}
}
...和使用反射的通用版本:
static class JaxbUtil {
static <T> T copy(Class<T> cls, T obj) throws InstantiationException, IllegalAccessException{
T copy = cls.newInstance();
for(Field f:cls.getDeclaredFields()){
XmlElement annotation = f.getAnnotation(XmlElement.class);
if(annotation != null && annotation.required()){
f.setAccessible(true);
f.set(copy, f.get(obj));
}
}
return copy;
}
}
我希望你明白为什么这可能会气馁。 像这样使用它:
YourJaxbClass theCopy = JaxbUtil.copy(YourJaxbClass.class, yourObjectToBeCopied);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.