Reputation: 2841
I have a class with JAXB annotations. The mandatory properties of the class have annotation @XmlElement(required = true). Is there a way to copy an object of the class to another object of the same class so that only the required properties would be copied and the optional ones would be nulls?
Thanks,
Update: I think that I need to clarify that I'm looking for a generic solution, i.e. the one that doesn't require knowing the class and the properties in advance.
Upvotes: 3
Views: 225
Reputation: 11944
An example of the copy() method:
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;
}
}
...and the generic version using reflection:
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;
}
}
I hope you see why this might be discouraged. Use it like this:
YourJaxbClass theCopy = JaxbUtil.copy(YourJaxbClass.class, yourObjectToBeCopied);
Upvotes: 2