用dom4j解析xml標籤,並將標籤屬性與文本內容添加進集合,創建方法,傳入action查找對應的id,從何獲取類路徑與方法,利用反射執行方法
FrameUtil.java
public class FrameUtil {
List<Student> list = new ArrayList();
public static void main(String[] args) throws Exception {
FrameUtil f = new FrameUtil();
f.executeMethod("2", f.jie());
}
private List<Student> jie() throws Exception {
// TODO Auto-generated method stub
Element root = new SAXReader().read(new File("./src/studentInfo.xml"))
.getRootElement();
Iterator<Element> it = root.elementIterator();
while (it.hasNext()) {
Student stu = new Student();
Element elStu = it.next();
stu.setId(elStu.attribute("id").getValue());
stu.setClassName(elStu.attribute("className").getValue());
stu.setMethod(elStu.attribute("method").getValue());
Iterator<Element> it2 = elStu.elementIterator();
while (it2.hasNext()) {
Element zi = it2.next();
if ("name".equals(zi.getName())) {
stu.setName(zi.getTextTrim());
}
if ("college".equals(zi.getName())) {
stu.setCollage(zi.getTextTrim());
}
if ("telephone".equals(zi.getName())) {
stu.setTelephone(zi.getTextTrim());
}
if ("notes".equals(zi.getName())) {
stu.setNotes(zi.getTextTrim());
}
}
list.add(stu);
}
for (Student s : list) {
System.out.println(s.getId() + " , " + s.getClassName() + " , "
+ s.getMethod() + " , " + s.getName() + " , "
+ s.getCollage() + " , " + s.getTelephone() + " , "
+ s.getNotes());
}
return list;
}
public Object executeMethod(String action, List<Student> para)
throws Exception {
String cname = "";
String method = "";
for (Student stu : list) {
if (stu.getId().equals(action))// 判斷id和action相同
{
// 獲取類名和方法
cname = stu.getClassName();
method = stu.getMethod();
break;// 跳出循環
}
}
Class<?> cl = Class.forName(cname);// 加載類名
Object obj = cl.newInstance();// 獲取對象
Method me = cl.getDeclaredMethod(method, List.class);// 獲取方法對象
Object objReturn = me.invoke(obj, para);// 執行方法
return objReturn;
}
}
UserDao1.java
public class UserDao1 {
public void add() {
System.out.println("正在調用add方法");
}
public String select(List<Object> list) {
System.out.println("正在調用select方法");
for (Object obj : list) {
System.out.println(obj);
}
return "ok";
}
}