Java根據實體快速生成對象


一、來源

  在寫代碼時總是遇到下面這種情況:

        Account account = new Account();
        account.setId();
        account.setGmtCreate();
        account.setGmtUpdate();
        account.setUsername();
        account.setPassword();
        account.setPhone();
        account.setEmail();
        account.setRoleIds();
        account.setType();
        account.setAccountNonExpired();
        account.setAccountNonLocked();
        account.setAccountExpiredDatetime();
        account.setLastPasswordResetDatetime();
        account.setTokenNonExpired();
        account.setVerificationCode();
        account.setVerificationCodeExpiredDatetime();
        account.setEnabled();
        account.setActive();
        account.setState();
View Code

  寫起來還費時,又容易遺漏,還特煩。於是抱着解決實際問題,搞了一個自動根據實體生成的工具,不是很好,以后再慢慢改進。

二、代碼

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class Quick {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        List<String> entityList = new LinkedList<>();
        String className = "";

        String nextStr = null;
        while (scanner.hasNext() && !(nextStr = scanner.next()).equals("!!")) {
            entityList.add(nextStr);
        }
        for (int i= 0;i<entityList.size();i++){
            if (entityList.get(i).equals("public")){
                if (i+2<entityList.size()&&entityList.get(i+1).equals("class")){

                    className = entityList.get(i+2);
                    break;
                }
            }
        }
        if (className==""){
            System.out.println("Entity decode fail!");
            System.exit(-1);
        }

        List<String> setMethodList = new LinkedList<>();
        for (String str:entityList){
            if (str.startsWith("set")){
                str = str.substring(0,str.indexOf("("));
                setMethodList.add(str);
            }
        }

        //格式輸出
        String lowerCaseClassName = toLowerCaseFirstOne(className);
        System.out.println(className+" "+lowerCaseClassName+" = new "+className+"();");
        for (String method:setMethodList){
            System.out.println(lowerCaseClassName+"."+method+"();");
        }
    }
    //首字母轉小寫
    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }
    //首字母轉大寫
    public static String toUpperCaseFirstOne(String s){
        if(Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }
}

 三、格式要求

  在IDea格式化之后輸入,Ctrl+shift+F


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM