xml如何解压java。尼奥。使用JAXB的路径?
我一直在尝试使用JAXB解压一些xml,但我不断收到错误:
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类,它调用默认构造函数并设置一些默认值
# 1 楼答案
你要找的是XmlAdapter和@XmlJavaTypeAdapter
您必须创建一个扩展XmlAdapter的类,比如XmlPathAdapter,实现抽象方法,然后需要使用@XmlJavaTypeAdapter(XmlPathAdapter.class)注释路径获取程序或字段
请参阅XmlAdapter文档以获取更多详细信息: http://docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/adapters/XmlAdapter.html
# 2 楼答案
这有两个部分,这两个部分都是工作所必需的:
由于
java.nio.file.Path is an interface, and JAXB can't handle interfaces.
错误,无法创建XmlAdapter<String, Path>
。因此,您必须使用XmlAdapter<String, Object>
,因为Object
是Path
的超类,所以它是有效的:然后必须在属性上使用非常特定的
@XmlElement
和@XmlJavaTypeAdapter
:type = Object.class
告诉JAXB将其序列化,就好像它是一个Object
,@XmlJavaTypeAdapter
表示对该特定字段使用该特定的Object
适配器,而不是另一个更通用的适配器