需求時幫別人寫了幾個接口葫盼,然后字段挺多的蛋勺,我都加了注釋瓦灶,但是不能給人家看類啊,當(dāng)時又沒有用swagger抱完,太懶了贼陶,所以就干脆根據(jù)注釋生成一個markdown字段說明表吧,一番折騰巧娱,搞個Demo
package com.server.simple.markdown;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ClassUtil;
import com.sun.javadoc.*;
import pers.conan.mdcoffee.exception.DisablePutException;
import pers.conan.mdcoffee.markdown.*;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
public class CustomerDoclet extends Doclet {
private static ClassDoc[] docClasses = null;
private static RootDoc docRoot = null;
public static boolean start(RootDoc root) {
ClassDoc[] classes = root.classes();
docRoot = root;
docClasses = classes;
//注釋文檔信息碉怔,自己愛怎么解析注釋就怎么解析了,看自己需求
return true;
}
public static void main(String[] args) throws Exception {
System.out.println(ClassUtil.getClassPathURL());
List<File> files = FileUtil.loopFiles("/Users/tony/workspace/IdeaProjects/Server/src/main/java/com/server/simple/entity");
List<String> filePaths = files.stream().map(file -> file.getAbsolutePath()).collect(Collectors.toList());
String[] docArgs =
new String[]{
"-private",
"-doclet", CustomerDoclet.class.getName()
};
for (String filePath : filePaths) {
docArgs = ArrayUtil.append(docArgs, filePath);
}
com.sun.tools.javadoc.Main.execute(docArgs);
show();
}
// 顯示DocRoot中的基本信息
public static void show() throws DisablePutException {
ClassDoc[] classes = docClasses;
TopMark content = new TopMark();
for (ClassDoc classDoc : classes) {
TableMark tableMark = handClass(classDoc);
TopMark top = new TopMark();
TitleMark titleMark = new TitleMark(tableMark.getText());
top.put(titleMark);
top.put(tableMark);
content.put(top);
}
FileUtil.writeString(content.translate(), FileUtil.file("/Users/tony/workspace/pro/markdown/完整.md"), "UTF-8");
}
public static TableMark handClass(ClassDoc classDoc) {
CustomTableMark tableMark = new CustomTableMark();
tableMark.setText(classDoc.commentText());
TableHeadMark headMark = new TableHeadMark(CollUtil.newArrayList(new CellMark("字段"), new CellMark("類型"), new CellMark("說明")));
tableMark.setHead(headMark);
for (FieldDoc field : classDoc.fields()) {
String type = field.type().simpleTypeName();
String comment = field.commentText();
String fieldName = field.name();
TableRowMark rowMark = new TableRowMark(CollUtil.newArrayList(new CellMark(fieldName), new CellMark(type), new CellMark(comment)));
tableMark.put(rowMark);
}
return tableMark;
}
}
注釋寫法必須是/**多行注釋的那種禁添,例子:
@Data
/**
* 測試用戶
*/
public class User {
/**
* 姓名
*/
public String name;
}
這里導(dǎo)出Markdown我用了大神寫的代碼:
https://gitee.com/ConanJordan/markdowncoffee
不過導(dǎo)出表格稍微有點Bug撮胧,自己改改就行了,就是那個表格頭的下一行--- 那種老翘,源代碼只加了一列芹啥,需要自己改改代碼,或者有時間提個merge吧酪捡。