从数据库获取数据,通过JavaBean。 数据转模型,中怎么使用内省 来节省代码。 求大师解答
常规的数据封装到bean对象中,都是调用get/set方法,但是如何对任意bean对象都能进行存储数据呢?这里就用到了内省,来获得bean对象的方法,与反射有些相像。
创建一个BeanUtils类
public static void populate(Object bean, Map<String, String[]> map) {
// bean是要存储的bean对象,map是数据
Set<Entry<String, String[]>> entrySet = map.entrySet();
for (Entry<String, String[]> entry : entrySet) {
String name = entry.getKey();
try {
PropertyDescriptor pd = new PropertyDescriptor(name, bean.getClass());
Method writeMethod = pd.getWriteMethod();//根据name获取其相应的set方法
writeMethod.invoke(bean, entry.getValue());//写入数据
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
一般的做法是通过类Introspector来获取某个对象的BeanInfo信息,然后通过BeanInfo来获取属性的描述器(PropertyDescriptor),通过这个属性描述器就可以获取某个属性对应的getter/setter方法,然后我们就可以通过反射机制来调用这些方法。
package com.itheima.util;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
public class WebUtil {
public static <T> T fillBean(HttpServletRequest request,
Class<T> class1) {
try {
T bean = class1.newInstance();
BeanUtils.populate(bean, request.getParameterMap());
return bean;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}