2016-04-06 34 views
3

我有一個包含JAXB註釋的類。 該類的強制屬性具有註解@XmlElement(required = true)。 有沒有辦法將類的對象複製到同一類的另一個對象,以便只複製所需的屬性,可選的屬性將是空值?JAXB:將只需要的屬性複製到對象中

感謝,

更新:我想我需要澄清,我正在尋找一個通用的解決方案,即不需要知道類和提前的屬性之一。

+3

我認爲你必須寫自己的'副本()'方法 – Dimi

+1

是的,有。要麼寫你自己的方法,就像@Dimi建議的那樣,或者如果你想一般地使用反射(這不是一個好的做法)。 – f1sh

+0

你能提供這樣的副本()的例子嗎? – spoonboy

回答

2

副本()方法的一個例子:

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); 
+0

我在f.set上遇到異常(...有JaxbUtil無法訪問類MyTest類型的成員,其修飾符「protected」。是否可以修改它以通過getters/setters使用受保護的屬性? – spoonboy

+0

已更新通過添加''setAccessible(true);''來回答 – f1sh

相關問題