Java反射——读取XML文件,创建对象

读取XML文件,创建对象

config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<!-- Cat类是个内部类 -->
	<bean id="id1" class="ahjava.p07reflect.Cat">
		<property name="username" value="英短" />
	</bean>
</beans>
import java.io.*;
import java.lang.reflect.Constructor;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class T35读取XML构造对象 {
	private static void get构造方法(String className, String pa1) throws Exception {
		Class<?> c = Class.forName(className);
		// 获取构造
		Constructor<?> constr = c.getConstructor(String.class);
		// 实例化对象
		Object o = constr.newInstance(pa1);
		System.out.println(o);
	}
	public static void main(String args[]) {
		/**
		 * 解析XML文件
		 */
		Element element = null;
		// 可以使用绝对路劲
		File f = new File("src/ahjava/config.xml");
		// documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件)
		DocumentBuilder db = null;
		DocumentBuilderFactory dbf = null;
		try {
			dbf = DocumentBuilderFactory.newInstance();
			db = dbf.newDocumentBuilder();
			Document dt = db.parse(f);// 得到一个DOM
			element = dt.getDocumentElement();
			String nodeName = element.getNodeName();
			System.out.println("根元素:" + nodeName);
			// 根元素下的所有子节点
			NodeList childNodes = element.getChildNodes();
			// 遍历这些子节点
			for (int i = 0; i < childNodes.getLength(); i++) {
				// 获得每个对应位置i的结点
				Node node1 = childNodes.item(i);
				if ("bean".equals(node1.getNodeName())) {
					String sClass = node1.getAttributes().getNamedItem("class").getNodeValue();
					System.out.println(sClass);
					// 获得<Accounts>下的节点
					NodeList nodeDetail = node1.getChildNodes();
					// 遍历<Accounts>下的节点
					for (int j = 0; j < nodeDetail.getLength(); j++) {
						// 获得<Accounts>元素每一个节点
						Node detail = nodeDetail.item(j);
						if ("property".equals(detail.getNodeName())) {
							String sV = detail.getAttributes().getNamedItem("value").getNodeValue();
							System.out.println("property: " + sV);
							get构造方法(sClass, sV);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
根元素:beans
ahjava.p07reflect.Cat
property: 英短
Cat构造:英短
ahjava.p07reflect.Cat@5ca881b5
原文地址:https://www.cnblogs.com/tigerlion/p/11182847.html