1. 程式人生 > >Java根據實體快速生成物件

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