@Getter
@Setter
public class ClassDocDefinition {
private List resultDocList;
private int maxLevel;
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class ResultDoc {
//参数名
private String paramName;
//类型
private String paramType;
//是否必填
private String require;
//默认值
private String defaultValue;
//说明
private String description;
//参数层级
private int level;
}
}
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.math.BigDecimal; import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.Temporal; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; public class ClassDocParser{ private final Class annotation; private final Function descFunc; private final Function isRequireFunc; private final Function defaultValueFunc; private List list; private AtomicInteger counter; protected ClassDocParser(Class annotation, Function descFunc, Function isRequireFunc, Function defaultValueFunc) { this.annotation = annotation; this.descFunc = descFunc; this.isRequireFunc = isRequireFunc; this.defaultValueFunc = defaultValueFunc; } public ClassDocDefinition parser(Type clz) { this.list = new ArrayList<>(); this.counter = new AtomicInteger(0); if (isClass(clz)) { parseClass(clz, 1); } else { nestedListMap(clz, 1); } ClassDocDefinition definition = new ClassDocDefinition(); definition.setMaxLevel(this.counter.get()); definition.setResultDocList(this.list); return definition; } private void parseClass(Type tp, int level) { if (tp == null) return; Class> clz = (Class>) tp; String typeofclz = typeof(clz); if (basicType.contains(typeofclz)) { this.counter.set(Math.max(this.counter.get(), level)); this.list.add(new ClassDocDefinition.ResultDoc("<" + typeofclz + ">", typeofclz, "Y", "", "嵌套内部值", level)); return; } Field[] fields = clz.getDeclaredFields(); for (Field field : fields) { T annotation = field.getAnnotation(this.annotation); String desc = descFunc.apply(annotation); String isRequire = isRequireFunc.apply(annotation); String defaultValue = defaultValueFunc.apply(annotation); Class> type = field.getType(); String name = field.getName(); String typeof = typeof(type); this.list.add(new ClassDocDefinition.ResultDoc(name, typeof, isRequire, defaultValue, desc, level)); this.counter.set(Math.max(this.counter.get(), level)); Class> nested = null; if ("list".equals(typeof) || "map".equals(typeof)) { Type genericType = field.getGenericType(); nestedListMap(genericType, level + 1); } else if ("array".equals(typeof)) { nested = type.getComponentType(); } else if ("object".equals(typeof)) { nested = type; } else if ("set".equals(typeof)) { Type genericType = field.getGenericType(); ParameterizedType pt = (ParameterizedType) genericType; nested = (Class>) pt.getActualTypeArguments()[0]; } parseClass(nested, level + 1); } } private void nestedListMap(Type genericType, int level) { String typeof = typeof(genericType); if (level == 1 && list.size() == 0 && !"object".equals(typeof)) { this.list.add(new ClassDocDefinition.ResultDoc("<" + typeof + ">", typeof, "", "", "", level)); this.counter.set(Math.max(this.counter.get(), level)); level = level + 1; } if ("list".equals(typeof)) { ParameterizedType pt = (ParameterizedType) genericType; Type typeArgument = pt.getActualTypeArguments()[0]; if (isClass(typeArgument)) { parseClass(typeArgument, level); } else { String reType = typeof(typeArgument); this.list.add(new ClassDocDefinition.ResultDoc("<" + reType + ">", reType, "", "", "", level)); this.counter.set(Math.max(this.counter.get(), level)); if ("list".equals(reType) || "map".equals(reType)) { nestedListMap(typeArgument, level + 1); } } } else if ("map".equals(typeof)) { // 解决key key只能是string 或者 int long 其他不管 ParameterizedType pt = (ParameterizedType) genericType; Type[] actualTypeArguments = pt.getActualTypeArguments(); String keyType = typeof(actualTypeArguments[0]); Type valueTypeArgument = actualTypeArguments[1]; String valueType = typeof(valueTypeArgument); keyType = basicType.contains(keyType) ? keyType : "object"; this.list.add(new ClassDocDefinition.ResultDoc("key", keyType, "Y", "", "", level)); this.list.add(new ClassDocDefinition.ResultDoc("value", valueType, "Y", "", "", level)); this.counter.set(Math.max(this.counter.get(), level)); if ("list".equals(valueType) || "map".equals(valueType)) { nestedListMap(valueTypeArgument, level + 1); } else { parseClass(valueTypeArgument, level); } } else if ("object".equals(typeof)) { // 跳过自定义对象的泛型 Type actualTypeArgument = ((ParameterizedTypeImpl) genericType).getActualTypeArguments()[0]; if (isClass(actualTypeArgument)) { parseClass(actualTypeArgument, level); } else { nestedListMap(actualTypeArgument, level); } } } private static final Set basicType = new HashSet<>(); static { basicType.add("int"); basicType.add("boolean"); basicType.add("string"); basicType.add("float"); basicType.add("double"); basicType.add("bigdecimal"); basicType.add("long"); basicType.add("enum"); basicType.add("Timestamp"); } private static String typeof(Type tp) { if (tp instanceof Class) { Class> type = (Class>) tp; if (type == Boolean.class || type == boolean.class) return "boolean"; if (type == Character.class || type == char.class) return "string"; if (type == Float.class || type == float.class) return "float"; if (type == Double.class || type == double.class) return "double"; if (type == BigDecimal.class) return "bigdecimal"; if (type == Timestamp.class) return "Timestamp"; if (type == Long.class || type == long.class) return "long"; if (type == Byte.class || type == byte.class) return "int"; if (type == Short.class || type == short.class) return "int"; if (type == Integer.class || type == int.class) return "int"; if (type == Void.class) return ""; if (type.isArray()) return "array"; if (type == Date.class || type == LocalDate.class || type == LocalDateTime.class) return "date"; try { if (type.isAssignableFrom(Date.class)) return "date"; if (type.isAssignableFrom(Temporal.class)) return "date"; } catch (Exception ignored) { } if (type.isInterface()) { if (type == CharSequence.class) return "string"; if (type == List.class) return "list"; if (type == Map.class) return "map"; if (type == Set.class) return "set"; } Class>[] interfaces = type.getInterfaces(); if (interfaces.length > 0) { for (Class> anInterface : interfaces) { if (anInterface == CharSequence.class) return "string"; if (anInterface == List.class) return "list"; if (anInterface == Map.class) return "map"; if (anInterface == Set.class) return "set"; } } if (type.isEnum()) { return "enum"; } return "object"; } else if (tp instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) tp; Type rawType = type.getRawType(); Class> aClass = (Class>) rawType; if (aClass.isInterface()) { if (aClass == CharSequence.class) return "string"; if (aClass == List.class) return "list"; if (aClass == Map.class) return "map"; if (aClass == Set.class) return "set"; } Class>[] interfaces = aClass.getInterfaces(); if (interfaces.length > 0) { for (Class> anInterface : interfaces) { if (anInterface == CharSequence.class) return "string"; if (anInterface == List.class) return "list"; if (anInterface == Map.class) return "map"; if (anInterface == Set.class) return "set"; } } } return "object"; } private static boolean isClass(Type tp) { return !(tp instanceof ParameterizedType); } public static ClassDocParserBuilder builder(){ return new ClassDocParserBuilder(); } public static class ClassDocParserBuilder{ public static class SubBuilder { private final Class annotation; private Function descFunc; private Function isRequireFunc; private Function defaultValueFunc; public SubBuilder(Class annotation) { this.annotation = annotation; } public SubBuilder descFunc(Function descFunc) { this.descFunc = descFunc; return this; } public SubBuilder isRequireFunc(Function isRequireFunc) { this.isRequireFunc = isRequireFunc; return this; } public SubBuilder defaultValueFunc(Function defaultValueFunc) { this.defaultValueFunc = defaultValueFunc; return this; } public ClassDocParser build() { return new ClassDocParser<>(annotation, descFunc, isRequireFunc, defaultValueFunc); } } public SubBuilder annotation(Class annotation) { return new SubBuilder<>(annotation); } } }
import java.util.List;
import java.util.stream.IntStream;
public class DocMarkDownRender {
public static String renderAsParam(ClassDocDefinition classDocDefinition) {
return Render.of(classDocDefinition, true).getResult();
}
public static String renderAsReturn(ClassDocDefinition classDocDefinition) {
return Render.of(classDocDefinition, false).getResult();
}
private static class Render {
private StringBuilder stringBuilder;
private ClassDocDefinition classDocDefinition;
private boolean isParam;
private String result;
private static Render of(ClassDocDefinition classDocDefinition, boolean isParam) {
Render render = new Render();
render.stringBuilder = new StringBuilder();
render.isParam = isParam;
render.classDocDefinition = classDocDefinition;
render.render();
return render;
}
private void render() {
List resultDocList = classDocDefinition.getResultDocList();
table(() -> {
tr(() -> {
td_span_bold(1, "参数名");
td_bold("类型");
if (isParam) {
td_bold("必填");
td_bold("默认值");
}
td_bold("说明");
});
resultDocList.forEach(s -> {
tr(() -> {
td_span(s.getLevel(), s.getParamName());
td(s.getParamType());
if (isParam) {
td(s.getRequire());
td(s.getDefaultValue());
}
td(s.getDescription());
});
});
});
this.result = stringBuilder.toString();
}
private void table(JustDo justDo) {
stringBuilder.append("");
justDo.done();
stringBuilder.append("n
");
}
private void tr(JustDo... justDos) {
stringBuilder.append("nt");
for (JustDo justDo : justDos) {
justDo.done();
}
stringBuilder.append("nt ");
}
private void td(String content) {
stringBuilder.append("ntt").append(content).append(" ");
}
private void td_bold(String content) {
stringBuilder.append("ntt").append("").append(content).append("").append(" ");
}
private void td_span(int currentLevel, String content) {
int emptyTd = currentLevel - 1;
int span = this.classDocDefinition.getMaxLevel() - emptyTd;
IntStream.range(0, emptyTd).forEach(a -> this.stringBuilder.append("ntt "));
stringBuilder.append("ntt")
.append(content)
.append(" ");
}
@SuppressWarnings("all")
private void td_span_bold(int currentLevel, String content) {
int emptyTd = currentLevel - 1;
int span = this.classDocDefinition.getMaxLevel() - emptyTd;
IntStream.range(0, emptyTd).forEach(a -> this.stringBuilder.append("ntt "));
stringBuilder.append("ntt")
.append("").append(content).append(" ");
}
@FunctionalInterface
interface JustDo {
void done();
}
public String getResult() {
return result;
}
}
}
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class DocUtil {
public static String[] parseMethod(Class> controller, String method){
Method[] methods = controller.getDeclaredMethods();
List collect = Arrays.stream(methods).filter(m -> m.getName().equals(method)).collect(Collectors.toList());
if (collect.size() > 1){
throw new RuntimeException("根据传入方法名找到的方法不是一个");
}
Method mt = collect.get(0);
ClassDocParser<> docParser = ClassDocParser.builder()
.annotation(ApiModelProperty.class)
.defaultValueFunc(property -> "")
.descFunc(property -> property == null ? "" :property.value())
.isRequireFunc(property -> property == null ? "" : property.required() ? "Y" : "N")
.build();
ClassDocDefinition definitionP = docParser.parser( mt.getParameters()[0].getParameterizedType());
ClassDocDefinition definitionR = docParser.parser(mt.getGenericReturnType());
return new String[]{ DocMarkDownRender.renderAsParam(definitionP) , DocMarkDownRender.renderAsReturn(definitionR)};
}
}
public class App {
public static void main(String[] args) {
DocUtil.parseMethod(TestController.class, "getUser");
}
}
输出后的字符串复制到typro下渲染出来



