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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM