`
bwlcool
  • 浏览: 19754 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

通过反射生成RequestParams

阅读更多
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;
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics