内省是反射的一种特例
由于在框架底层中要频繁地操作javabean,而利用反射操作比较麻烦。所以为了方便操作javabean,sun公司开发出一套API提高效率
Java内省机制是针对JavaBean进行操作的
public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } private int age; }
public class TestIntrospector { @Test public void tes1() throws Exception { Class cl = Class.forName("com.irish.aop.cc.Person"); //在bean上进行内省 BeanInfo beaninfo = Introspector.getBeanInfo(cl, Object.class); PropertyDescriptor[] pro = beaninfo.getPropertyDescriptors(); Person p = new Person(); System.out.print("Person的属性有:"); for (PropertyDescriptor pr : pro) { System.out.print(pr.getName() + " "); } System.out.println(""); for (PropertyDescriptor pr : pro) { Method writeme = pr.getWriteMethod(); if (pr.getName().equals("name")) { writeme.invoke(p, "xiong"); } if (pr.getName().equals("age")) { writeme.invoke(p, 23); } Method method = pr.getReadMethod(); System.out.print(method.invoke(p) + " "); } } @Test public void test2() throws Exception { PropertyDescriptor pro = new PropertyDescriptor("name", Person.class); Person preson=new Person(); Method method=pro.getWriteMethod(); method.invoke(preson, "xiong"); System.out.println(pro.getReadMethod().invoke(preson)); }}
怎么让后台的Model对象统一的接收表单提交过来的参数
Servlet
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); user u=new user(); populate(request.getParameterMap(),u); System.out.println(u); } private void populate(Mapmap,user u){ try { Map params=map; //1 获得 java Bean的描述信息 BeanInfo info =Introspector.getBeanInfo(user.class); //2 获得 User中的属性信息 PropertyDescriptor [] pds =info.getPropertyDescriptors(); //3 遍历属性信息 for (PropertyDescriptor pd : pds) { String[] param=params.get(pd.getName()); if (param!=null && param.length>0) { pd.getWriteMethod().invoke(u, param[0]); } } } catch (Exception e) { e.printStackTrace(); } }
JavaBean
public class user { private String name; private String password; public user(){ super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "user [name=" + name + ", password=" + password + " ]"; }}
Jsp