Loads the object from the XML file via JAXB - Java XML

Java examples for XML:JAXB

Description

Loads the object from the XML file via JAXB

Demo Code

/*/*from  ww  w  . j  a va  2s.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.
 */
//package com.java2s;

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 Tutorials