反射收集註解標註的值

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;
    }
}
相關文章
相關標籤/搜索