public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { // 利用反射封装数据 // 1、获取所有数据 Map<String, String[]> map = req.getParameterMap(); // 2、封装学生对象 Student stu = new Student(); // 2.1遍历map集合 for (String key : map.keySet()) { String[] values = map.get(key); // 2.2获取Student对象的属性描述器(获取属性的get\set方法对象) PropertyDescriptor pd = new PropertyDescriptor(key, stu.getClass()); // 2.3获取对应的set方法对象 Method setMethod = pd.getWriteMethod(); // 2.4执行方法 if (values.length > 1) setMethod.invoke(stu, (Object)values); else setMethod.invoke(stu, values); } System.out.println(stu); } catch (Exception e) { e.printStackTrace(); } }
public class Student { private String userName; private String age; private String[] hobby; private boolean sec; public Student() {} public Student(String userName, String age, String[] hobby) { this.userName = userName; this.age = age; this.hobby = hobby; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } @Override public String toString() { return "Student {userName=" + userName + ", age=" + age + ", hobby=" + Arrays.toString(hobby) + "}"; } }
标签:userName,反射,封装,String,age,获取,Student,hobby,public From: https://www.cnblogs.com/weiduaini/p/17244772.html