Java tutorial
//package com.java2s; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.*; import java.util.HashMap; import java.util.Map; public class Main { private static final ThreadLocal<Map<Class<?>, Unmarshaller>> uMapLocal = new ThreadLocal<Map<Class<?>, Unmarshaller>>() { @Override protected Map<Class<?>, Unmarshaller> initialValue() { return new HashMap<Class<?>, Unmarshaller>(); } }; /** * XML to Object * @param <T> T * @param clazz clazz * @param xml xml * @return T */ public static <T> T convertToObject(Class<T> clazz, String xml) { return convertToObject(clazz, new StringReader(xml)); } /** * XML to Object * @param <T> T * @param clazz clazz * @param inputStream inputStream * @return T */ public static <T> T convertToObject(Class<T> clazz, InputStream inputStream) { return convertToObject(clazz, new InputStreamReader(inputStream)); } /** * XML to Object * @param <T> T * @param clazz clazz * @param reader reader * @return T */ @SuppressWarnings("unchecked") public static <T> T convertToObject(Class<T> clazz, Reader reader) { try { Map<Class<?>, Unmarshaller> uMap = uMapLocal.get(); if (!uMap.containsKey(clazz)) { JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); uMap.put(clazz, unmarshaller); } return (T) uMap.get(clazz).unmarshal(reader); } catch (JAXBException e) { e.printStackTrace(); } return null; } }