我现在的需求是,写一个方法,参数传入任意对象类型,返回这个对象的属性名称和属性值的map
解决方案 »
- 仍然是中文乱码问题
- tomcat datasource的配置问题
- select值以数组形式传递的问题
- 在jsp中实现缓存,欢迎进来讨认
- onchange= "javascript:form1.submit()"表示什么意思呀,在线!!!!1
- 单jsp开发还有前途吗?
- 打印网页的问题
- 关于JB8和Struts的配置问题。解决者给50分
- 求助TT项目报错The requested resource (/blog/) is not available.如何解决
- 100 (continue) read timeout. Resume sending the request问题
- 我在做struts项目 报这个错是什么意思 请各位高手翻译下 谢谢了
- 如何将String类型的数组传入另一个jsp页面中?
if (o == null)
return null; try { map = new HashMap<String, String>(); BeanInfo bInfo = Introspector.getBeanInfo(o.getClass());
PropertyDescriptor propertyDescriptorp[] = bInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptorp.length; i++) {
PropertyDescriptor propertyDescriptor = propertyDescriptorp[i];
if (!"class".equalsIgnoreCase(propertyDescriptor.getName().trim())) {
Method m = propertyDescriptor.getReadMethod();
Object result = m.invoke(o);
if (result == null)
result = "null";
map.put(propertyDescriptor.getName(), result.toString());
}
} } catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} return map;
}
package com.study.reflect;import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;public class CommonManager { /**
* @param object
* @return
*/
public static Map getObjectAllArgs(Object object) throws Exception{
//获取对象的class对象
Class<?> classType = object.getClass();
//获取对象的所有申明过的field
Field[] fields = classType.getDeclaredFields();
Map map = new HashMap();
//拼接所有field
for(Field field : fields){
//属性名字
String name = field.getName();
String first = name.substring(0, 1);
String getMethodName = "get" + first.toUpperCase() + first.substring(1);
Method method = classType.getDeclaredMethod(getMethodName, new Class[]{});
Object value = method.invoke(object, new Object[]{});
map.put(field.getName(), value);
}
return map;
}
}对象要有get方法,且get方法满足getXxx()
改为
String getMethodName = "get" + first.toUpperCase() + name.substring(1);
也简单啊 instanceof 下对象 然后递归