Here you can find the source of convertToObject(Class
Parameter | Description |
---|---|
T | a parameter |
clazz | a parameter |
inputStream | a parameter |
public static <T> T convertToObject(Class<T> clazz, InputStream inputStream)
//package com.java2s; //License from project: Apache License 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//from w ww . java 2s . com protected Map<Class<?>, Unmarshaller> initialValue() { return new HashMap<>(); } }; /** * XML to Object * @param <T> * @param clazz * @param xml * @return */ public static <T> T convertToObject(Class<T> clazz, String xml) { return convertToObject(clazz, new StringReader(xml)); } /** * XML to Object * @param <T> * @param clazz * @param inputStream * @return */ public static <T> T convertToObject(Class<T> clazz, InputStream inputStream) { return convertToObject(clazz, new InputStreamReader(inputStream)); } /** * XML to Object * @param <T> * @param clazz * @param reader * @return */ @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; } }