java - 如何使用 JAXB 解码 java.nio.Path?

标签 java xml jaxb nio

我一直在尝试使用 JAXB 解码一些 xml,但我不断收到错误:

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

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

我的类(class):

@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<String, Path>由于java.nio.file.Path is an interface, and JAXB can't handle interfaces.错误。因此您必须使用XmlAdapter<String, Object> ,自 Object 起生效是 Path 的父类(super class):

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适用于该特定字段的适配器,而不是另一个更通用的适配器。

关于java - 如何使用 JAXB 解码 java.nio.Path?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37842702/

相关文章:

java - 计算给定字符串中的数字

java - XMLUnit - 比较时忽略 'id' 属性

java - 通过用户设置更改应用程序中特定文本的字体

xml - 如何将 Lua 函数添​​加到 Notepad++ functionList.XML

java - 如何配置 persistence.xml 以指向 MongoDB

java - 使用 jaxb 解码元素属性和文本以分隔字段

java - ERROR : Property appears in @XmlType. propOrder,但不存在此类属性

java - Jaxb 中 int 变量的用法

java - 从 MATLAB 调用 Java?

java - 更改 JSpinner 中的日期