Here you can find the source of unmarshalInstance(final String data, final Class
public static <T> T unmarshalInstance(final String data, final Class<T> expectedType)
//package com.java2s; /*/* ww w .j a v a 2s. c om*/ * #%L * cobertura-metrics-model * %% * Copyright (C) 2013 Cobertura * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import java.io.StringReader; public class Main { public static <T> T unmarshalInstance(final String data, final Class<T> expectedType) { try { // Assume we should only unmarshal a single type. final JAXBContext ctx = JAXBContext.newInstance(expectedType); final Unmarshaller unmarshaller = ctx.createUnmarshaller(); // To ignore the namespace and xml element localPart, // unmarshal the instance as a JAXBElement. final StreamSource streamSource = new StreamSource(new StringReader(data)); final JAXBElement<T> jaxbElement = unmarshaller.unmarshal(streamSource, expectedType); // All done. return jaxbElement.getValue(); } catch (JAXBException e) { throw new RuntimeException(e); } } }