线程" main"中的例外情况javax.xml.bind.JAXBException:无法实例化提供程序com.sun.xml.bind.v2.ContextFactory

时间:2014-10-25 01:00:50

标签: jaxb marshalling

我试图测试JAXB unmarshaller / marshaller。这是我的代码

JAXBContext context = JAXBContext.newInstance(ClientUser.class.getPackage().getName());

我的实体代码

@XmlRootElement(name = "user")
public class ClientUser {
    private String name;

    public ClientUser() {}

    public ClientUser(String name) {
        this.name = name;
    }

    @XmlElement(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

即使我向实体类添加工厂类

@XmlRegistry
class ObjectFactory {
    ClientUser createPerson() {
        return new ClientUser();
    }
}

我仍然继续得到此异常

Exception in thread "main" javax.xml.bind.JAXBException: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: javax.xml.bind.JAXBException: "com.example.ws.poc.entity" doesnt contain ObjectFactory.class or jaxb.index
 - with linked exception:
[javax.xml.bind.JAXBException: "com.example.ws.poc.entity" doesnt contain ObjectFactory.class or jaxb.index]
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:146)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:335)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:431)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:394)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:298)

如何解决此错误?

2 个答案:

答案 0 :(得分:3)

JAXB实现不进行包扫描。如果从包名称引导带,JAXB将在新行上查找ObjectFactory(带有@XmlRegistry注释)或jaxb.index文件,其中包含短类名。

如果您没有这两项,则可以在域类本身上创建JAXBContext

JAXBContext jc = JAXBContext.newInstance(Foo.class, Bar.class);

答案 1 :(得分:0)

您还可以从要反序列化的类的类型中获取上下文。见下文:

public class XmlDeserializer implements Deserializer {
  public <T> T deserialize(String input, Class<T> outputType)
    throws DeserializationException {
    try {
      JAXBContext jc = JAXBContext.newInstance(outputType);
      Unmarshaller unmarshaller = jc.createUnmarshaller();
      StringReader reader = new StringReader(input);
      return outputType.cast(unmarshaller.unmarshal(reader));
    } catch (JAXBException e) {
      throw new DeserializationException(e.getMessage(), e);
    }
  }
}