1. 程式人生 > >利用反射,將java bean物件轉換成md檔案的表格

利用反射,將java bean物件轉換成md檔案的表格

一個有趣的小功能:可能有些時候需要寫文件,需要將java的一些物件(vo/po/do/dto等)的屬性和屬性型別提取出來,以表格的形式展示.

java物件:

package com.test;

/**
 * Created by Administrator on 2018/8/31.
 */
public class User {
    private String userName;
    private String sex;
    private Integer age;

    public String getUserName() {
        return
userName; } public void setUserName(String userName) { this.userName = userName; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return age; } public void
setAge(Integer age) { this.age = age; } }

主函式:

import com.test.DirectShipAddressVO;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;

public class Main {

    public static String reflect(Class<?> obj, String content) {
        Field[] fields = obj.getDeclaredFields();
        for
(int i = 0; i < fields.length; i++) { String name = fields[i].getName(); Class<?> type = fields[i].getType(); String typeRes = ""; if (type != null) { String tmp = type.getName(); typeRes = tmp.substring(tmp.lastIndexOf('.')+1, tmp.length()); } content += "|" + name + "|" + typeRes + "|||\r\n"; //System.out.print("|" + name + "|" + typeRes + "|||\r\n"); } return content; } public static void saveAsFileWriter(String content, String classsName) { classsName = classsName.substring(classsName.lastIndexOf('.')+1, classsName.length()); String savefile = "F:\\workspace\\reflect\\" + classsName + ".md"; FileWriter fwriter = null; try { File file = new File(savefile); if(!file.exists()) { file.createNewFile(); } fwriter = new FileWriter(savefile); fwriter.write(content); } catch (IOException ex) { ex.printStackTrace(); } finally { try { fwriter.flush(); fwriter.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public static void main(String[] args) { Class<User> obj = User.class; String content = "####資料庫文件\r\n\r\n|欄位資訊|型別|中文說明|備註資訊|\r\n|-----|-----|-----|-----|\r\n"; String res = reflect(obj, content); System.out.println(res); saveAsFileWriter(res,obj.getName()); } }

markdown檔案:

####資料庫文件

|欄位資訊|型別|中文說明|備註資訊|
|-----|-----|-----|-----|
|userName|String|||
|sex|String|||
|age|Integer|||

結果展示:
這裡寫圖片描述