XStream类
1.首先了解包结构(引用其它第三方包 XStream-1.4.7.jar)
com.thoughtworks.xstream;
2.常用的方法
2.1 Class(java.lang.Class)转 string
XStream xstream = new XStream(newDomDriver("UTF-8", new XmlFriendlyNameCoder("-_","_")));
stream.alias("xml",tClass);
Objcet object=xstream .fromXML(str)
2.2 string 转Objce
XStream xstream = new XStream(newDomDriver("UTF-8", new XmlFriendlyNameCoder("-_","_")));
stream.alias("xml",tClass);
String xmlStr=xstream .toXML(str)
3.线程安全
原因:
查看源码HierarchicalStreamDriver为顶层抽象类,那fromXML举例代码如下:
我们不难发现调用了this.hierarchicalStreamDriver.createReader(input)
这个实现代码如下
注意选中的部分,这个方法的需要使用了同步锁而且使用了工厂反射获取对象并且使用了单例模式,这是保证这个类安全的主要代码
4.解决方案
根据 换为类型(class) 创建单例模式
public class XStreamFactory {
private static volatile Map
private static volatile XStream xStream = null;
public static XStreamgetStream(Class tClass) {
XStream stream=null;
if(streamMap.containsKey(tClass.getName())) {
stream=streamMap.get(tClass.getName());
}else {
stream = new XStream(newDomDriver("UTF-8", new XmlFriendlyNameCoder("-_","_")));
stream.alias("xml", tClass);
streamMap.put(tClass.getName(),stream);
}
return stream;
}
public static XStreamgetXStream(){
if (xStream== null) {
xStream = new XStream(newDomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
}
return xStream;
}
}