用于指定Java类和返回对象的XML文件
我有一个基于Maven和Spring的javaweb应用程序 在src/main/resources中,我有一个XML文件 sourceconfig.xml用于指定Java类和返回对象的XML文件,java,xml,spring,Java,Xml,Spring,我有一个基于Maven和Spring的javaweb应用程序 在src/main/resources中,我有一个XML文件 sourceconfig.xml <?xml version="1.0" encoding="UTF-8"?> <sourceConfig area="Defects"> <adapterObject>jAdapter</adapterObject> <resultObject>jsonObject
<?xml version="1.0" encoding="UTF-8"?>
<sourceConfig area="Defects">
<adapterObject>jAdapter</adapterObject>
<resultObject>jsonObject</resultObject>
</sourceConfig>
我能够将xml解析为对象
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;
}
}
它工作得很好
但都是弦。一些我想要的东西。例如,在XML中,我提到了jsonObject
我有一个类com.myapp.config.JsonObject.java
因此,如果我提到这样的类,那么就不要使用jsonObject
<resultObject class="com.myapp.config.JsonObject">jsonObject</resultObject>
jsonObject
或者以其他方式提到类,我应该能够在我的SourceConfig中获得一个JsonObject对象,我该怎么做呢?使用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();
该类可以更改。对于另一个XML或另一个配置,将有另一个类。因此,我无法知道在运行时需要将类型强制转换到哪个类。在这里,您可以对其进行类型转换以进行测试。如果是另一门课呢。如果我知道它是哪个类,就不需要xml文件。我可以使用
new
操作创建对象,您可以避免强制转换并以对象类型简单地返回它。或者可以使用泛型编写方法。对不起,我应该在哪里做?仅在解组后?在解析XML到POJO时,是否有任何方式可以将其转换为Object?如果适配器对象是简单的POJO,则可以直接进行解组。因为封送/解封送仅将对象的状态保存在文件中。所以你必须按照我提到的方式来做。
SourceAdapterConfig config = new SourceAdapterConfig();
Object adapterObject = config.getAdapterObject();