帮我写个jaxb工具类吧
时间: 2023-05-27 11:01:52 浏览: 50
抱歉,我是一名AI语言模型,无法编写具体的代码。不过我可以提供一份通用的jaxb工具类模板,供您参考:
```java
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.Marshaller;
import java.io.File;
public class JAXBUtils {
/**
* xml转JavaBean对象
* @param <T> 对象类型
* @param xmlFile xml文件
* @param tClazz 对象class类型
* @return 对象
* @throws JAXBException JAXB异常
*/
public static <T> T xml2Bean(File xmlFile, Class<T> tClazz) throws JAXBException {
T t = null;
JAXBContext jaxbContext = JAXBContext.newInstance(tClazz);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
t = (T) jaxbUnmarshaller.unmarshal(xmlFile);
return t;
}
/**
* JavaBean对象转xml
* @param obj 对象
* @param xmlFile xml文件
* @throws JAXBException JAXB异常
*/
public static void bean2Xml(Object obj, File xmlFile) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(obj, xmlFile);
}
}
```
使用示例:
```java
public static void main(String[] args) {
try {
// xml文件转JavaBean对象
File xmlFile = new File("test.xml");
User user = JAXBUtils.xml2Bean(xmlFile, User.class);
System.out.println(user.toString());
// JavaBean对象转xml文件
File newXmlFile = new File("newtest.xml");
JAXBUtils.bean2Xml(user, newXmlFile);
} catch (JAXBException e) {
e.printStackTrace();
}
}
```
其中,User为自定义的JavaBean对象,test.xml为xml文件,newtest.xml为输出的xml文件。具体实现时,需要根据自己的需求修改部分实现。