[java]代码库
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtilsBean;
public class Conversion {
/**
* 通过Java反射的机制动态的获取bean中的值,比较繁琐,后面有一个更简单的方法去做这些工作
* @param bean
* @return
* @throws Exception
*/
public static <T> Map<String, Object> conversionToMap (T bean)
throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
Class <? extends Object > classType = bean.getClass();
Field[] fields = classType.getDeclaredFields();
for (Field f : fields) {
String fieldName = f.getName();
if (!"serialVersionUID".equals (fieldName) ) {
String strLetter = fieldName.substring (0, 1).toUpperCase();
String getName = "get" + strLetter + fieldName.substring (1);
Method getMethod = classType.getMethod (getName, new Class[] {});
Object methodReturn = getMethod.invoke (bean, new Object[] {});
String value = methodReturn == null ? "" : methodReturn
.toString();
map.put (fieldName, value);
}
}
return map;
}
/**
* 这里我们使用了第三方的工具类,可以帮之我们省去很多工作量,例如我们不需要自己通过反射的方法去获取bean中
* 属性的值,PropertyUtilsBean可以帮我们搞定一切
* @param bean
* @return
* @throws Exception
*/
public static <T> Map<String, Object> conversionToMapByTool (T bean) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors (bean);
for (PropertyDescriptor d : descriptors) {
String fieldName = d.getName();
Object value = propertyUtilsBean.getNestedProperty (bean, fieldName);
if (!"class".equals (fieldName) ) {
map.put (fieldName, value);
}
}
return map;
}
public static void main (String[] args) throws Exception {
TestBean bean = new TestBean();
bean.setAddress ("Addrss");
bean.setName ("Name");
bean.setSex ("Man");
try {
Map<String, Object> map1 = Conversion.conversionToMap (bean);
System.out.println (map1.toString() );
Map<String, Object> map2 = Conversion.conversionToMapByTool (bean);
System.out.println (map2.toString() );
} catch (Exception e) {
e.printStackTrace();
}
}
}
初级程序员
by: 云代码会员 发表于:2013-04-21 15:06:58 顶(0) | 踩(0) 回复
学习下反射,谢谢提供资源
回复评论