XML工具之JAXB

JAXB作为XML的处理工具,其中JAXBContext.newInstance重复多次,性能会严重下降;使用线程安全的集合保存对象,可避免此类问题。

package cn.uce.oms.common.util;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.concurrent.ConcurrentHashMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import cn.uce.base.exception.BusinessException;
import cn.uce.oms.common.exception.TracePushException;

/**
 * 
 * @Description: xml实体互转工具类
 * @author Martin
 * @date 2018年4月26日 上午12:46:30
 */
public class JAXBUtil {

	static ConcurrentHashMap<String, JAXBContext> jaxbContextMap = new ConcurrentHashMap<String, JAXBContext>();

	/**
	 * 
	 * @Description: java实体类转xml
	 * @param obj
	 * @param encode
	 *            编码格式
	 * @param format
	 *            是否格式化生成的xml串
	 * @param fragment
	 *            是否省略xm头声明信息
	 * @return
	 * @author Martin
	 * @date 2018年4月26日 上午12:48:08
	 */
	public static String toXML(Object obj, String encode, boolean format, boolean fragment) {
		try {
			JAXBContext jaxbContext = jaxbContextMap.get(obj.getClass().getName());
			if (jaxbContext == null) {
				jaxbContext = JAXBContext.newInstance(obj.getClass());
				jaxbContextMap.put(obj.getClass().getName(), jaxbContext);
			}

			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_ENCODING, encode);
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, format);
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, fragment);
			StringWriter writer = new StringWriter();
			marshaller.marshal(obj, writer);
			return writer.toString();
		} catch (Exception e) {
			LogUtil.error("java实体类转xml异常", e);
			throw new BusinessException("java实体类转xml异常");
		}
	}

	/**
	 * xml转java实体类
	 */
	@SuppressWarnings("unchecked")
	public static <T> T fromXML(String xml, Class<T> valueType) {
		try {
			JAXBContext jaxbContext = jaxbContextMap.get(valueType.getName());
			if (jaxbContext == null) {
				jaxbContext = JAXBContext.newInstance(valueType);
				jaxbContextMap.put(valueType.getName(), jaxbContext);
			}
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			return (T) unmarshaller.unmarshal(new StringReader(xml));
		} catch (Exception e) {
			LogUtil.error("java实体类转xml异常", e);
			throw new BusinessException("java实体类转xml异常");
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值