您的位置:首页 > 移动开发 > Objective-C

java反射获取object类中的属性

2018-03-07 09:43 246 查看

参考资料:http://blog.csdn.net/nihaoqiulinhe/article/details/53838874

以下开始是正文————–分割线—————-

做项目的时候遇到一个问题,要求写一个通用的工具包,传入一个list,然后获取list里面的数据。问题来了,既然是通用的,就不能指定类,最多是
list<object>
这种。

不会做的时候就度娘之

public static void exportFile(HashMap map, List exportData, String fileds[]){
for (int j = 0; exportData != null && !exportData.isEmpty()
&& j < exportData.size(); j++) {
Class clazz = exportData.get(j).getClass();
String[] contents = new String[fileds.length];
//fileds是object的属性,调用本方法的时候传入
for (int i = 0; fileds != null && i < fileds.length; i++) {
String filedName = toUpperCaseFirstOne(fileds[i]);
//将例如name的属性转化为getName这种方法
Object obj = null;
try {
Method method = clazz.getMethod(filedName);
method.setAccessible(true);
obj = method.invoke(exportData.get(j));
} catch (Exception e) {

}
String str = String.valueOf(obj);
//str即为name的值
if (str == null || str.equals("null"))
str = "";
contents[i] = str;
}

}
}


将第一个字母转换为大写字母并和get拼合成方法

/**
* 将第一个字母转换为大写字母并和get拼合成方法
*
* @param origin
* @return
*/
private static String toUpperCaseFirstOne(String origin) {
StringBuffer sb = new StringBuffer(origin);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
sb.insert(0, "get");
return sb.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: