一、来源
在写代码时总是遇到下面这种情况:
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();
写起来还费时,又容易遗漏,还特烦。于是抱着解决实际问题,搞了一个自动根据实体生成的工具,不是很好,以后再慢慢改进。
二、代码
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