【问题标题】:NPE when using extension of a generic class in JAXB / Resteasy在 JAXB / Resteasy 中使用泛型类扩展时的 NPE
【发布时间】:2012-11-11 10:42:10
【问题描述】:

我正在使用 RestEasy 2.3.4。我遇到了NPE。我有一个通用基类 ValueContainer,我计划通过用适当的类型替换通用参数来将其扩展为 StringValue、IntegerValue、BooleanValue 等。

我正在尝试使用扩展类作为数据传输对象,如下所示。但是,我在 JAXB 处理中遇到了 NPE。这意味着,我没有正确对待 JAXB 中的扩展类。请指教。正确的方法是什么?谢谢。

基类:

@XmlAccessorType(XmlAccessType.FIELD)
public class ValueContainer<T> {
  @XmlAttribute
  protected T value;

  public ValueContainer() {
  }

  public ValueContainer(T value) {
    this.value = value;
  }

  public T getValue() {
    return value;
  }

  public void setValue(T value) {
    this.value = value;
  }
}

示例扩展类:

@XmlRootElement (name="integervalue")
public class IntegerValue extends ValueContainer<Integer> {

  public IntegerValue() {
  }

  public IntegerValue(Integer value) {
    super(value);
  }
}

jax-rs API 接口:

@GET
@Path("/status/{what}")
IntegerValue getStatus(@PathParam ("what")Integer what) ;

API 实现:

@Override
public
IntegerValue getStatus(Integer what) {
  return new IntegerValue(what);
}

当我的浏览器调用 http:.../status/1 时,配置返回 null 的原因:

package org.jboss.resteasy.plugins.providers.jaxb;

.....
protected JAXBContext createContextObject(Annotation[] parameterAnnotations, Class... classes) throws JAXBException
{
  JAXBConfig config = FindAnnotation.findAnnotation(parameterAnnotations, JAXBConfig.class);
  return new JAXBContextWrapper(config, classes);
}

【问题讨论】:

    标签: java rest jaxb jax-rs resteasy


    【解决方案1】:

    我认为你应该在public ValueContainer() 中抛出一个异常。这个 ctor 存在只是因为 JAXB 要求我们有公共的无参数构造函数(参见 What JAXB needs a public no-arg constructor for?)。发生的情况是您的对象在没有任何参数的情况下被实例化,并且value 保持为空(奇怪的是您的 Java 编译器没有抱怨)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多