简体   繁体   中英

Is it possible to dynamically declare a java pojo class from xml configuration file?

Is it possible to dynamically declare java pojo bean classes from an xml config file?

Say if the config file is like - A.xml:

   <xml>
    <memberValues>
    <memberValue>
    <dataType>String</dataType>
    <name>productName</name>
    <value>Hello World!</value>
    </memberValue>
    <memberValue>
    <dataType>Double</dataType>
    <name>productPrice</name>
    <value>31.99</value>
    </memberValue>
    ...
    <memberValues>
    </xml>

It should declare a new java pojo bean class on the fly like - A.java:

   public class A{
    private String productName = "Hello World!";
    private Double productPrice = 31.99;

    //getters and setters
    ...
    }

Your best bet is to generate Java source code and invoke the JavaCompiler class. See http://docs.oracle.com/javase/7/docs/api/javax/tools/JavaCompiler.html

You can do it using JAXB java APIs,

if your xml is like,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>  
<employee id="1">  
    <name>User</name>  
    <salary>50000.0</salary>  
</employee>  

then you can use following java code for converting xml file to java object

    JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);    

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();    
    Employee e=(Employee) jaxbUnmarshaller.unmarshal(file); 

for more information you can see the link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM