Java 怎么通过JAXB从XML文件加载对象

2019年7月21日19:57:45Java 怎么通过JAXB从XML文件加载对象已关闭评论 782 609字阅读2分1秒

1.简介

Java 怎么通过JAXB从XML文件加载对象?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

 


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

import javax.xml.bind.Unmarshaller;

public class Main {
    
    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;
    }
}

 
编程十万个怎么办