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

如何使用JAXB解组java.nio.Path?,java,xml,jaxb,nio,Java,Xml,Jaxb,Nio,我一直在尝试使用JAXB对一些xml进行解组,但我一直遇到错误: java.nio.file.Path是一个接口,JAXB无法处理接口。 有没有办法告诉JAXB如何从字符串构建路径 我的班级: @XmlRootElement public class Project extends OutputConfiguration { private Path sourceDir; private Path buildDir; private String name; /

我一直在尝试使用JAXB对一些xml进行解组,但我一直遇到错误:

java.nio.file.Path是一个接口,JAXB无法处理接口。

有没有办法告诉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类,它调用默认构造函数并设置一些默认值。

您要查找的是XmlAdapter和@XmlJavaTypeAdapter

您必须创建一个扩展XmlAdapter的类,比如XmlPathAdapter,实现抽象方法,然后需要使用@XmlJavaTypeAdapter(XmlPathAdapter.class)注释路径获取者或字段

请参阅XmlAdapter文档以获取示例和更多详细信息:

这有两个部分,这两个部分都是工作所必需的:


您无法创建
XmlAdapter
,因为
java.nio.file.Path是一个接口,JAXB无法处理接口。
错误。因此,您必须使用
XmlAdapter
,因为
Object
Path
的一个超类,所以它可以工作:

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

type=Object.class
告诉JAXB将其序列化,就好像它是一个
对象一样,
@XmlJavaTypeAdapter
说对该特定字段使用特定的
对象
适配器,而不是另一个更通用的适配器。

这不起作用,因为
java.nio.file.Path是一个接口,JAXB不能处理接口。
,JDK也不提供Path的公共实现。
@XmlJavaTypeAdapter(NioPathAdaptor.class)
@XmlElement(type = Object.class)
private Path sourceDir;