简体   繁体   English

在JAXB / Resteasy中使用泛型类的扩展时的NPE

[英]NPE when using extension of a generic class in JAXB / Resteasy

I am using RestEasy 2.3.4. 我正在使用RestEasy 2.3.4。 I am encountering NPE. 我遇到了NPE。 I have a generic base class ValueContainer, which I plan to extend as StringValue, IntegerValue, BooleanValue, etc, by substituting the generic param with the appropriate type. 我有一个泛型基类ValueContainer,我计划通过用适当的类型替换泛型参数来扩展为StringValue,IntegerValue,BooleanValue等。

I am experimenting with using the extension classes as the data transfer objects as illustrated with the following. 我正在尝试使用扩展类作为数据传输对象,如下所示。 However, I am encountering NPE at JAXB processing. 但是,我在JAXB处理中遇到NPE。 Which means, I am not treating extension classes in JAXB correct. 这意味着,我没有正确处理JAXB中的扩展类。 Please advise. 请指教。 What is the right way to do it? 做正确的方法是什么? Thank you. 谢谢。

Base class: 基类:

@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;
  }
}

Example extension class: 示例扩展类:

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

  public IntegerValue() {
  }

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

The jax-rs API interface: jax-rs API接口:

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

The API impl: API impl:

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

Cause of NPE, where config returns null, when my browser calls http:.../status/1: NPE的原因,当我的浏览器调用http:... / status / 1时,config返回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);
}

I think you should throw an exception in public ValueContainer() . 我认为你应该在public ValueContainer()抛出异常。 This ctor is there only because JAXB requires us to have public no-arg constructors (see What JAXB needs a public no-arg constructor for? ). 这个ctor只是因为JAXB要求我们拥有公共的无参数构造函数(请参阅什么JAXB需要公共的无参数构造函数? )。 What happens is that your object is instantiated without any argument and value remains null (it's strange your Java compiler doesn't complain). 发生的事情是你的对象被实例化而没有任何参数,并且value保持为null(奇怪的是你的Java编译器没有抱怨)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM