public static RequestParams getRequestParamsFromObject(Object obj) {
RequestParams params = new RequestParams();
Class classType = obj.getClass();
Field[] fields = classType.getDeclaredFields();
if (fields != null) {
int length = fields.length;
for (int i = 0; i < length; i++) {
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
Method getMethod = classType.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(obj, new Object[] {});
if (value instanceof File) {
try {
params.put(fieldName, (File) value);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
params.put(fieldName,
value != null ? String.valueOf(value)
: (String) null);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
return params;
}
通过反射生成RequestParams

最新推荐文章于 2022-07-15 14:32:30 发布
