我有一個包含JAXB註釋的類。 該類的強制屬性具有註解@XmlElement(required = true)。 有沒有辦法將類的對象複製到同一類的另一個對象,以便只複製所需的屬性,可選的屬性將是空值?JAXB:將只需要的屬性複製到對象中
感謝,
更新:我想我需要澄清,我正在尋找一個通用的解決方案,即不需要知道類和提前的屬性之一。
我有一個包含JAXB註釋的類。 該類的強制屬性具有註解@XmlElement(required = true)。 有沒有辦法將類的對象複製到同一類的另一個對象,以便只複製所需的屬性,可選的屬性將是空值?JAXB:將只需要的屬性複製到對象中
感謝,
更新:我想我需要澄清,我正在尋找一個通用的解決方案,即不需要知道類和提前的屬性之一。
副本()方法的一個例子:
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);
我認爲你必須寫自己的'副本()'方法 – Dimi
是的,有。要麼寫你自己的方法,就像@Dimi建議的那樣,或者如果你想一般地使用反射(這不是一個好的做法)。 – f1sh
你能提供這樣的副本()的例子嗎? – spoonboy