之前有碰到一个需求,要求将数据库查询的数据输出为markdown文件。遇到的主要问题是List<T>转markdown表格。主要思路如下:
- 创建注解,用于标记对象字段对应的表头名称和顺序
- 根据注解生成表头
- 根据注解将T的对应值按顺序生成字符串
- 将表头和内容字符串拼接
创建注解
/** 定义注解*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FiledInfo{
// 指定对应的表头名称
String alias() default "";
// 指定顺序
int order() default -1;
}
主要代码
private static final String SEP_ROW = " ----- |";
private static final String SEP = "|";
private static final String BLANK = "";
/** list内容转为markdown表格*/
public static <T> String convertTable(List<T> list, Class<T> clazz){
Field[] fields = clazz.getFields();
if(fields.length == 0){
fields = clazz.getDeclaredFields();
}
// 对字段排序
List<Field> fieldList = new ArrayList<>(Arrays.asList(fields));
fieldList.removeIf( e-> getAnnotation(e) == null);
fieldList.sort(Comparator.comparingInt(e -> getAnnotation(e).order()));
StringBuilder markdown = new StringBuilder();
// 生成表头
markdown.append(initTableHead(fieldList));
// 生成分隔行
markdown.append(initSepRow(fieldList.size()));
// 添加表格内容
list.forEach(e->{
StringBuilder row = new StringBuilder(SEP);
fieldList.forEach(field ->{
try {
Object object = fieldGetMethod(field,clazz).invoke(e);
row.append(object == null ? BLANK : object).append(SEP);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
throw new RuntimeException(ex);
}
});
row.append("\n");
markdown.append(row);
});
return markdown.toString();
}
/** 初始化表头*/
private static String initTableHead(List<Field> fieldList) {
StringBuilder builder = new StringBuilder(SEP);
fieldList.forEach(e-> builder.append(getAnnotation(e).alias()).append(SEP));
builder.append("\n");
return builder.toString();
}
/** 生成分隔行*/
private static String initSepRow(int size) {
StringBuilder builder = new StringBuilder(SEP);
for(int i = 0;i<size;i++){
builder.append(SEP_ROW);
}
builder.append("\n");
return builder.toString();
}
测试
@Data
public class CustomBean{
@MarkdownUtil.FiledInfo(alias = "姓名",order = 0)
private String name;
@MarkdownUtil.FiledInfo(alias = "性别",order = 3)
private String gender;
@MarkdownUtil.FiledInfo(alias = "年龄",order = 2)
private String age;
@MarkdownUtil.FiledInfo(alias = "国籍",order = 5)
private String nation;
@MarkdownUtil.FiledInfo(alias = "职业",order = 4)
private String job;
public CustomBean(String name, String gender, String age, String nation, String job){
this.name = name;
this.gender = gender;
this.age = age;
this.nation = nation;
this.job = job;
}
}
public static void main(String[] args) {
List<CustomBean> list =new ArrayList<>();
list.add(new CustomBean("LiLei","male","25","China","worker"));
System.out.println(convertTable(list, CustomBean.class));
}
网友评论