1. 程式人生 > >利用反射來自動生成簡單的接口文檔

利用反射來自動生成簡單的接口文檔

oid null ttr 自動 get 接口測試 hashmap obj exception

一:簡介
以前做項目提供接口時,每一個接口文檔都是手寫,手寫接口文檔有很多不足,比如:寫接口文檔比較消耗時間,參數首字母是小寫,如果將參數直接復制到word文檔,第一個字母有時候是大寫,或者復制參數時,有些參數忘記復制等,把有問題的文檔發給前端的同事,他們也會非常抱怨,這樣團隊的氣氛也不好,所以後來漸漸發覺,其實這些工作可以利用java的反射來幫我們完成,我們只需要寫一些參數描述,就能生成接口文檔,另外接口的測試方法也可以利用反射來完成,這樣可以有效的提高工作效率。

  效果圖如下:

  //程序生成的word,沒有樣式,你可以手動設置樣式

技術分享

//控制層圖片

技術分享

二:代碼
1)利用反射來獲取某個controller下的某個方法,以及該方法的參數,參數類型。


//接口測試的map
Map<String, StringBuilder> serviceTestMap = new HashMap<String, StringBuilder>();
//接口所有的參數Map<參數key, 參數類型>
Map<String, Object> methodParams = new LinkedHashMap<String, Object>();
try {
            Class clazz = Class.forName(className);
            ClassPool pool 
= ClassPool.getDefault(); List paramsType = new ArrayList(); CtClass cc = pool.get(clazz.getName()); Method method[] = clazz.getDeclaredMethods(); for (Method m : method) { String methodName = m.getName(); if (!methodMap.containsKey(methodName)) {
continue; } paramsType = new ArrayList(); Class[] cParams = m.getParameterTypes(); for (Class cType : cParams) { //此處的包是,我們系統封裝後的包名,你可以註釋這些代碼 if (cType.getName().equals("im.core.mvc.controller.IModel") || cType.getName().equals("im.core.dao.Dao")|| cType.getName().equals("lj.sys.UserToken")) { continue; } paramsType.add(cType.getName()); } index = 0; CtMethod cm = cc.getDeclaredMethod(methodName); MethodInfo methodInfo = cm.getMethodInfo(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute .getAttribute(LocalVariableAttribute.tag); if (attr == null) { // exception } String[] paramNames = new String[cm.getParameterTypes().length]; int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1; for (int i = 0; i < paramNames.length; i++) paramNames[i] = attr.variableName(i + pos); for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; if (paramName.equals("model") || paramName.equals("dao")|| paramName.equals("userToken")) { if(paramName.equals("dao")){ methodParams.put("paramsStatus",1); } continue; } methodParams.put(paramNames[i], paramsType.get(index) .toString()); if (serviceTestMap.containsKey(methodName)) { serviceTestMap.get(methodName).append( paramNames[i] + ","); } else { sb = new StringBuilder(); sb.append(paramNames[i] + ","); serviceTestMap.put(methodName, sb); } index++; } params.put(methodName, methodParams); methodParams = new LinkedHashMap<String, Object>(); } Iterator iterator = serviceTestMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Entry) iterator.next(); createRequest(service, entry.getValue().toString(), entry .getKey().toString(), 0); }

2:)自動生成接口測試的方法

public StringBuffer createRequest(String service, String msg,
            String method, int type) {
        StringBuffer sb = new StringBuffer("public void " + method + "(){")
                .append("\r\n");
        sb.append("Map<String, Object> params = new HashMap<String, Object>();");
        sb.append("\r\n");
        sb.append("NetworkBean networkBean = new NetworkBean();    ");
        sb.append("\r\n");
        sb.append("int index=1;"); 
        String msgArr[] = msg.split(",");
        for (String m : msgArr) {
            sb.append("params.put(\"" + m + "\", index);");
            sb.append("\r\n");
            sb.append("index++;");
            sb.append("\r\n");
        } 
            sb.append(
                    "HttpClientManager.getInstance().sendRequest(\"" + URL
                            + service + "/" + method
                            + ".htm\",params, networkBean);").append("\r\n"); 
        sb.append("System.out.println(networkBean.getCode()+\",\"+networkBean.getResult()); ");
        sb.append("}");
        log.info(sb.toString());
        return sb;
    }

3:)程序自動生成的測試方法

public void query() {
        Map<String, Object> params = new HashMap<String, Object>();
        NetworkBean networkBean = new NetworkBean();
        int index = 1;
        params.put("status", index);
        index++;
        HttpClientManager.getInstance().sendRequest(
                "http://127.0.0.1:8080/publicsh//user/query.htm", params,
                networkBean);
        System.out.println(networkBean.getCode() + ","
                + networkBean.getResult());
    }

    public void save() {
        Map<String, Object> params = new HashMap<String, Object>();
        NetworkBean networkBean = new NetworkBean();
        int index = 1;
        params.put("name", index);
        index++;
        params.put("passWord", index);
        index++;
        params.put("paramsStatus", index);
        index++;
        params.put("age", index);
        index++;
        HttpClientManager.getInstance().sendRequest(
                "http://127.0.0.1:8080/publicsh//user/save.htm", params,
                networkBean);
        System.out.println(networkBean.getCode() + ","
                + networkBean.getResult());
    }

代碼完整下載地址:github

利用反射來自動生成簡單的接口文檔