如何使用JAXB解组java.nio.Path?

时间:2016-06-15 18:06:13

标签: java xml jaxb nio

我一直试图使用JAXB解组一些xm​​l,但我一直收到错误:

java.nio.file.Path is an interface, and JAXB can't handle interfaces.

有没有办法告诉JAXB如何从字符串构建路径?

我的课程:

@XmlRootElement
public class Project extends OutputConfiguration {
    private Path sourceDir;
    private Path buildDir;
    private String name;

    /**
     * Get the root directory of the sources.
     * This will be used as the working directory for the build.
     *
     * @return the path
     */
    public Path getSourceDir() {
        return sourceDir;
    }

    /**
     * Get the root directory of the sources.
     *
     * @param sourceDir the path
     */
    @XmlElement
    public void setSourceDir(Path sourceDir) {
        this.sourceDir = sourceDir;
    }

    /**
     * Get the build directory.
     * This is the directory where all outputs will be placed.
     *
     * @return the path
     */
    public Path getBuildDir() {
        return buildDir;
    }

    /**
     * Set the build directory.
     *
     * @param buildDir this is the directory where all outputs will be placed.
     */
    @XmlElement
    public void setBuildDir(Path buildDir) {
        this.buildDir = buildDir;
    }

    /**
     * Get the friendly name of the project.
     *
     * @return the name of the project
     */
    public String getName() {
        return name;
    }

    /**
     * Set the friendly name of the project.
     *
     * @param name the name
     */
    @XmlElement(required = true)
    public void setName(String name) {
        this.name = name;
    }
}

我创建了一个ObjectFactory类,它调用默认构造函数并设置一些默认值。

2 个答案:

答案 0 :(得分:1)

这有两部分,要使该功能正常工作,这两个部分都是必需的:


由于出现XmlAdapter<String, Path>错误,因此无法创建java.nio.file.Path is an interface, and JAXB can't handle interfaces.。因此,您必须使用XmlAdapter<String, Object>,它可以工作,因为ObjectPath的超类:

public class NioPathAdaptor extends XmlAdapter<String, Object> {
    public String marshal(Object v) {
        if (!(v instanceof Path)) {
            throw new IllegalArgumentException(...);
        ...

然后,您必须在属性上使用非常具体的@XmlElement@XmlJavaTypeAdapter

@XmlJavaTypeAdapter(NioPathAdaptor.class)
@XmlElement(type = Object.class)
private Path sourceDir;

type = Object.class告诉JAXB将此序列化为Object,而@XmlJavaTypeAdapter则说对该特定字段使用特定的Object适配器另一个更通用的适配器。

答案 1 :(得分:0)

您正在寻找的是XmlAdapter和@XmlJavaTypeAdapter。

你必须创建一个扩展XmlAdapter的类,比如XmlPathAdapter,实现抽象方法,然后你需要使用@XmlJavaTypeAdapter(XmlPathAdapter.class)注释你的Path getter或字段。

查看XmlAdapter文档以获取更多详细信息的示例: http://docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/adapters/XmlAdapter.html