功能就是将对象,比如User,Teacher通过JaxbContext这个转化为xml,并且返回这个xml字符串
import java.io.StringWriter;import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;public class JaxbContextUtil { private static JAXBContext context =null;
private static Marshaller m = null;
//将对象转化为xml
public static String objectToXml(Object obj) {
StringWriter sw = new StringWriter();
try {
context = JAXBContext.newInstance(Object.getClass());
m = context.createMarshaller();
m.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8");
m.marshal(obj , sw);
} catch (JAXBException e) {
e.printStackTrace();
}
return sw.toString();
}
}
多线程会有问题吗?
import java.io.StringWriter;import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;public class JaxbContextUtil { private static JAXBContext context =null;
private static Marshaller m = null;
//将对象转化为xml
public static String objectToXml(Object obj) {
StringWriter sw = new StringWriter();
try {
context = JAXBContext.newInstance(Object.getClass());
m = context.createMarshaller();
m.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8");
m.marshal(obj , sw);
} catch (JAXBException e) {
e.printStackTrace();
}
return sw.toString();
}
}
多线程会有问题吗?
第一个线程设置了context,第两个线程在前一个线程没处理完又将context改变了。
context设为局部变量就行。