-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXMLUtil.java
More file actions
75 lines (67 loc) · 2.59 KB
/
XMLUtil.java
File metadata and controls
75 lines (67 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package designpattern.util;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
public class XMLUtil {
public static final File CONFIG_FILE = new File("src\\designpattern\\util\\config.xml");
/**
* 该方法用于从XML配置文件中提取具体类类名,并返回一个实例对象
* @param TagName 标签名
* @return
*/
public static Object getBean(String TagName) {
try {
String cName = getTagValue(TagName);
return newInstance(cName);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 返回相应的标签名里的内容
* @param TagName 标签名
* @return 标签名里的内容
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public static String getTagValue(String TagName) throws ParserConfigurationException, SAXException, IOException {
//创建文档对象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(CONFIG_FILE);
//获取包含类名的文本节点
// doc.getDocumentElement().getElementsByTagName("className").item(0).getFirstChild().getNodeValue()
NodeList nl = doc.getElementsByTagName(TagName);
Node classNode = nl.item(0).getFirstChild();
return classNode.getNodeValue();
}
/**
* 通过类名生成实例对象并将其返回
* @param className 完整的类名
* @return
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
*/
public static Object newInstance(String className) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
//
Class c = Class.forName(className);
Object obj = c.getDeclaredConstructor().newInstance();
return obj;
}
public static void main(String[] args) throws Exception {
System.out.println(XMLUtil.getTagValue("className"));
System.out.println(XMLUtil.getTagValue("className2"));
System.out.println(XMLUtil.getTagValue("className3"));
}
}