指定Java类和返回对象的XML文件

时间:2014-03-03 08:41:07

标签: java xml spring

我有一个Maven&基于Spring的Java Web应用程序

在src / main / resources中,我有一个XML文件。

sourceconfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<sourceConfig area="Defects">
    <adapterObject>jAdapter</adapterObject>
    <resultObject>jsonObject</resultObject>
</sourceConfig>

我有一个POJO用于​​此 SourceConfig.java

@XmlRootElement
public class SourceConfig {
    String area;
    String adapterObject;
    String resultObject;

    public String getArea() {
        return area;
    }

    @XmlAttribute
    public void setArea(String area) {
        this.area = area;
    }

    public String getAdapterObject() {
        return adapterObject;
    }

    @XmlElement
    public void setAdapterObject(String adapterObject) {
        this.adapterObject = adapterObject;
    }

    public String getResultObject() {
        return resultObject;
    }

    @XmlElement
    public void setResultObject(String resultObject) {
        this.resultObject = resultObject;
    }
}

我能够将xml解析为object。

public class SourceAdapterConfig {

    public SourceConfig getConfigObject() throws JAXBException, IOException {
        JAXBContext jaxbContext = JAXBContext.newInstance(SourceConfig.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

        Resource resource=new ClassPathResource("sourceconfig.xml");
        File file=resource.getFile();

        SourceConfig sourceConfig = (SourceConfig) jaxbUnmarshaller.unmarshal(file);
        return sourceConfig;
    }
}

工作正常。

但都是String。有些我想作为对象。例如,在XML中我提到了<resultObject>jsonObject</resultObject>

我有一个班级com.myapp.config.JsonObject.java

所以,而不是<resultObject>jsonObject</resultObject>如果我提这样的课

<resultObject class="com.myapp.config.JsonObject">jsonObject</resultObject> 

或其他一些提及类的方法,我应该能够在 SourceConfig 中获得 JsonObject 对象我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用java反射

Class theClass = Class.forName("com.example.Test");
Test testObject = (Test)theClass.newInstance();

这将创建一个com.example.Test的实例。

在您的背景下,

public class SourceAdapterConfig {

    private SourceConfig config;

    private SourceConfig getConfigObject() throws JAXBException, IOException {
        JAXBContext jaxbContext = JAXBContext.newInstance(SourceConfig.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

        Resource resource=new ClassPathResource("sourceconfig.xml");
        File file=resource.getFile();

        SourceConfig sourceConfig = (SourceConfig) jaxbUnmarshaller.unmarshal(file);
        return sourceConfig;
    }

    public SourceAdapterConfig(){
        config = getConfigObject();
    }

    public Object getAdapterObject(){
        String adapterClassName = config.getAdapterObject();
        Class theClass = Class.forName(adapterClassName);
        return theClass.newInstance();
 }
}

用法:

SourceAdapterConfig config = new SourceAdapterConfig();
Object adapterObject = config.getAdapterObject();