代码语言:javascript复制
public class RequestParamParse {
private RequestParamParse() {
}
/**
* 解析请求参数返回为Key-Value
*
* @param request
* @return
* @throws Exception
*/
public static ConcurrentHashMap<String, Object> parseParam(BaseRequest request) throws Exception {
ConcurrentHashMap<String, Object> result = new ConcurrentHashMap();
Field[] fields = request.getClass().getDeclaredFields();
for (Field f : fields) {
if (!f.isAnnotationPresent(RequestParam.class)) {
continue;
}
f.setAccessible(true); // 开启暴力反射
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), request.getClass());
Method readMethod = pd.getReadMethod();
if (String[].class == f.getType()) {
AtomicInteger replace = new AtomicInteger(0); // 需要替换数组中的占位符N.
for (String s : (String[]) readMethod.invoke(request)) {
if(s == null || s.length() < 1){
continue;
}
result.put(f.getAnnotation(RequestParam.class).key()
.replace("N", replace.getAndIncrement() ""), s);
}
continue;
}
// 收集处理结果
result.put(f.getAnnotation(RequestParam.class).key(), readMethod.invoke(request));
}
return result;
}
}