Java XML JAXB Unserialize loadObject(Path path, Class clazz)

Here you can find the source of loadObject(Path path, Class clazz)

Description

Loads the object from the file.

License

Apache License

Parameter

Parameter Description
T the object type.
path the XML file.
clazz the class of the object.

Return

the corresponding object.

Declaration

public static <T> T loadObject(Path path, Class<T> clazz) 

Method Source Code

//package com.java2s;
/*//from   ww w. j  a  v  a2s. c  o  m
 * Copyright 2015 Andrej_Petras.
 *
 * 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.
 */

import java.nio.file.Path;
import javax.xml.bind.JAXBContext;

import javax.xml.bind.Unmarshaller;

public class Main {
    /**
     * Loads the object from the file.
     *
     * @param <T> the object type.
     * @param path the XML file.
     * @param clazz the class of the object.
     * @return the corresponding object.
     */
    public static <T> T loadObject(Path path, Class<T> clazz) {
        T result;
        if (path == null || clazz == null) {
            throw new RuntimeException("The path to file or class is null!");
        }

        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            result = (T) jaxbUnmarshaller.unmarshal(path.toFile());
        } catch (Exception ex) {
            throw new RuntimeException("Error loading the xml from path " + path.toString(), ex);
        }
        return result;
    }
}

Related

  1. load(Class clazz, InputStream is)
  2. load(File f, Class... args)
  3. load(final String xml, final Class clazz)
  4. load(InputStream input, Class type)
  5. loadObject(Class typeClass, URL path)
  6. loadXML(Class type, File sourceFile)
  7. loadXml(File file, Class requireType)
  8. loadXML(Object object, String fileNamePath)
  9. loadXMLFromString(Object object, String line)