【问题标题】:JAXB: copy only required properties to the objectJAXB:仅将所需的属性复制到对象
【发布时间】:2016-04-06 09:38:10
【问题描述】:

我有一个带有 JAXB 注释的类。 类的强制属性具有注释 @XmlElement(required = true)。 有没有办法将类的对象复制到同一类的另一个对象,以便只复制必需的属性而可选的属性为空?

谢谢,

更新:我认为我需要澄清我正在寻找一种通用解决方案,即不需要提前了解类和属性的解决方案。

【问题讨论】:

  • 我觉得你得自己写copy()方法
  • 是的,有。要么按照@Dimi 的建议编写您自己的方法,或者,如果您想通用地这样做,请使用反射(这不是一个好习惯)。
  • 你能提供一个这样的 copy() 的例子吗?

标签: java jaxb


【解决方案1】:

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

【讨论】:

  • 我在 f.set(... JaxbUtil 上遇到异常无法访问带有修饰符“protected”的 MyTest Type 类的成员。是否可以通过修改它以使用受保护的属性获取者/设置者?
  • 通过添加setAccessible(true);更新了答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-13
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多