我一直在尝试使用 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/