Here you can find the source of readObjectFromXml(Class
Parameter | Description |
---|---|
T | - return parameter type |
jaxbBindClass | - JAXB bind class |
xmlFileName | - XML filename |
Parameter | Description |
---|---|
JAXBException | if read XML faild |
public static <T> T readObjectFromXml(Class<T> jaxbBindClass, String xmlFileName) throws JAXBException
//package com.java2s; import java.io.InputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class Main { /**//ww w.j a v a 2s. c o m * read java object from XML. * * @param <T> - return parameter type * @param jaxbBindClass - JAXB bind class * @param xmlFileName - XML filename * @return JAXB bing object * * @throws JAXBException if read XML faild */ public static <T> T readObjectFromXml(Class<T> jaxbBindClass, String xmlFileName) throws JAXBException { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName); return readObjectFromXml(jaxbBindClass, is); } /** * read java object from XML. * * @param <T> - return parameter type * @param jaxbBindClass - JAXB bind class * @param is - XML input stream * @return JAXB bing object * @throws JAXBException if read XML faild */ @SuppressWarnings("unchecked") public static <T> T readObjectFromXml(Class<T> jaxbBindClass, InputStream is) throws JAXBException { Unmarshaller unmarshaller = createUnmarshaller(jaxbBindClass); return (T) unmarshaller.unmarshal(is); } @SuppressWarnings("rawtypes") private static Unmarshaller createUnmarshaller(Class jaxbBindClass) throws JAXBException { Unmarshaller unmarshaller = newJAXBContext(jaxbBindClass).createUnmarshaller(); return unmarshaller; } @SuppressWarnings("rawtypes") private static JAXBContext newJAXBContext(Class jaxbBindClass) throws JAXBException { return JAXBContext.newInstance(jaxbBindClass); } }