unmarshal generic method via JAXB - Java XML

Java examples for XML:JAXB

Description

unmarshal generic method via JAXB

Demo Code


//package com.java2s;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.StringReader;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class targetClass = String.class;
        String xml = "java2s.com";
        System.out.println(unmarshal(targetClass, xml));
    }//from   w w w  . ja  v a 2s . c  om

    public static <T> T unmarshal(Class<T> targetClass, String xml)
            throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(targetClass);
        Unmarshaller um = jc.createUnmarshaller();

        return (T) um.unmarshal(new StringReader(xml));
    }

    public static <T> T unmarshal(Class<T> targetClass, File xmlFile)
            throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(targetClass);
        Unmarshaller um = jc.createUnmarshaller();

        return (T) um.unmarshal(xmlFile);
    }
}

Related Tutorials