原
Java SE练习 - 对dom4j解析、反射的综合练习
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
前言:对dom4j、反射使用的一个综合练习。
一、编写XML文件
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<student className="cn.itcast.javaeevideoday02.Student">
<name>张三</name>
<age>18</age>
<sex>男</sex>
</student>
<student className="cn.itcast.javaeevideoday02.Student">
<name>李四</name>
<age>20</age>
<sex>男</sex>
</student>
<student className="cn.itcast.javaeevideoday02.Student">
<name>王五</name>
<age>22</age>
<sex>男</sex>
</student>
</beans>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
二、导入jar包
在项目下新建lib文件夹,将dom4j解析jar包复制到该路径,点击jar包右键BuildPath–>Add to buildpath
三、代码实现
package cn.itcast.javaeevideoday02;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
*
* @author 大家都说名字长不会被发现
*
*/
public class SynthesisDemo {
public static void main(String[] args) throws Exception {
//创建SAXReader对象
SAXReader reader = new SAXReader();
//读取XML文件
Document document = reader.read("bean.xml");
//获取文件跟标签
Element rootElement = document.getRootElement();
//获取根标签下指定的所有子标签
List<Element> elements = rootElement.elements();
//创建集合对象
ArrayList<Student> stuLists = new ArrayList<>();
for (Element element : elements) {
//获取标签属性值
String className = element.attributeValue("className");
//获取子标签文本
String name = element.elementText("name");
String age = element.elementText("age");
String sex = element.elementText("sex");
//获取字节码文件对象
Class c = Class.forName(className);
//获取对象满参构造
Constructor constructor = c.getConstructor(String.class,int.class,String.class);
Object student = constructor.newInstance(name,Integer.valueOf(age),sex);
stuLists.add((Student)student);
}
System.out.println(stuLists);
}
}
- 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
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e44c3c0e64.css" rel="stylesheet">
</div>
</article>