用action执行方法

用dom4j解析xml标签,并将标签属性与文本内容添加进集合,创建方法,传入action查找对应的id,从何获取类路径与方法,利用反射执行方法


FrameUtil.java

public class FrameUtil {
	List list = new ArrayList();

	public static void main(String[] args) throws Exception {
		FrameUtil f = new FrameUtil();
		f.executeMethod("2", f.jie());
	}

	private List jie() throws Exception {
		// TODO Auto-generated method stub
		Element root = new SAXReader().read(new File("./src/studentInfo.xml"))
				.getRootElement();
		Iterator 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 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 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 list) {
		System.out.println("正在调用select方法");
		for (Object obj : list) {
			System.out.println(obj);
		}
		return "ok";

	}
} 
  


你可能感兴趣的:(Java)