一个给pojo生成hashcode、equals、toString等方法的工具类

一个给pojo生成hashcode、equals、toString等方法的工具类

package com.kong.coder;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class CodeFactory {

public static void main(String[] args) {
String projectPath = "D:\\Workspaces\\MyEclipse 10\\lowcaActivity";
String packageName = "com.lowca.activity.pojo";
String[] banedClassNames = {};
appendCompareMethods(projectPath, packageName, banedClassNames);
}

public static void appendCompareMethods(String projectPath,
String packageName, final String[] banedClassNames) {
String packagePath = File.separator
+ packageName.replace(".", File.separator);
File packageFile = new File(projectPath + File.separator + "src"
+ packagePath);
if (!packageFile.exists() || !packageFile.isDirectory()) {
System.err.println("包文件不存在");
System.exit(-1);
}
File[] pojoFiles = packageFile.listFiles(new FilenameFilter() {

@Override
public boolean accept(File dir, String name) {
boolean isBaned = false;
for (String banedClassName : banedClassNames) {
if (name.equals(banedClassName + ".java")) {
isBaned = true;
break;
}
}
return !isBaned && name.endsWith(".java");
}
});
if (pojoFiles == null || pojoFiles.length == 0) {
System.err.println("包文件是空的,找不到pojo");
System.exit(-1);
}
for (File pojoFile : pojoFiles) {
handlePojoFile(packageName, pojoFile);
}
}

private static void handlePojoFile(String packageName, File pojoFile) {
String pojoFileName = pojoFile.getName();
String pojoClassName = packageName + "."
+ pojoFileName.substring(0, pojoFileName.length() - 5);
Class<?> pojoClass = null;
try {
pojoClass = Class.forName(pojoClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method[] methods = pojoClass.getMethods();
List<Method> getterList = new ArrayList<Method>();
// 遍历反射方法组并提取当前类属性的getter方法
for (Method method : methods) {
// 过滤与当前类属性无关的get方法
if (method.getName().startsWith("get")
&& !method.getName().equals("getClass")) {
getterList.add(method);
}
}
MethodnameFilter methodnameFilter = new MethodnameFilter() {

@Override
public boolean accept(String name) {
return name.matches("get([A-Z][a-zA-Z])*Id") ? false : true;
}
};
String hashCodeCode = getHashCodeCode(pojoClass, getterList,
methodnameFilter);
String equalsCode = getEqualsCode(pojoClass, getterList,
methodnameFilter);
String toStringCode = getToStringCode(pojoClass, getterList,
methodnameFilter);
String methodsCode = hashCodeCode + equalsCode + toStringCode;

writeCodeToPojoFile(methodsCode, pojoFile);
}

private static void writeCodeToPojoFile(String methodsCode, File pojoFile) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
FileReader fr = new FileReader(pojoFile);
br = new BufferedReader(fr);
String line;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line + "\r\n");
}
int pos = sb.lastIndexOf("}");
sb.insert(pos, methodsCode);

FileWriter fw = new FileWriter(pojoFile);
bw = new BufferedWriter(fw);
bw.write(sb.toString());
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}

try {
if (bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

private static String getEqualsCode(Class<?> pojoClass,
List<Method> getterList, MethodnameFilter methodnameFilter) {
StringBuffer sb = new StringBuffer();
sb.append("\n\tpublic boolean equals(Object object) {\n");
sb.append("\t\tif (this == object)\n");
sb.append("\t\t\treturn true;\n");
sb.append("\t\tif (!(object instanceof ${class}))\n");
sb.append("\t\t\treturn false;\n");
sb.append("\t\tfinal ${class} ${classLowercaseFirst} = (${class}) object;\n");
for (Method getter : getterList) {
String getterName = getter.getName();
if (methodnameFilter != null
&& !methodnameFilter.accept(getterName))
continue;
sb.append("\t\tif (!" + getterName
+ "().equals(${classLowercaseFirst}." + getterName
+ "()))\n");
sb.append("\t\t\treturn false;\n");
}
sb.append("\t\treturn true;\n");
sb.append("\t}\n");
String code = sb.toString();
String className = pojoClass.getSimpleName();
String classNameLowercaseFirst = toLowercaseFirst(className);
code = code.replaceAll("\\$\\{class\\}", className);
code = code.replaceAll("\\$\\{classLowercaseFirst\\}",
classNameLowercaseFirst);
return code;

}

private static String getHashCodeCode(Class<?> pojoClass,
List<Method> getterList, MethodnameFilter methodnameFilter) {
StringBuffer sb = new StringBuffer();
sb.append("\n\tpublic int hashCode() {\n");
sb.append("\t\tint result;\n");
boolean first = true;
for (Method getter : getterList) {
String getterName = getter.getName();
if (methodnameFilter != null
&& !methodnameFilter.accept(getterName))
continue;
if (first) {
first = false;
sb.append("\t\tresult = " + getterName + "().hashCode();\n");
} else {
sb.append("\t\tresult = 29 * result + " + getterName
+ "().hashCode();\n");
}
}
sb.append("\t\treturn result;\n");
sb.append("\t}\n");
String code = sb.toString();
return code;

}

private static String getToStringCode(Class<?> pojoClass,
List<Method> getterList, MethodnameFilter methodnameFilter) {
StringBuffer sb = new StringBuffer();
sb.append("\n\tpublic String toString() {\n");
boolean first = true;
for (Method getter : getterList) {
String getterName = getter.getName();
if (methodnameFilter != null
&& !methodnameFilter.accept(getterName))
continue;
String filedName = toLowercaseFirst(getterName.substring(3));
if (first) {
first = false;
sb.append("\t\treturn \"${class} [" + filedName + "=\" + "
+ filedName + "\n");
} else {
sb.append("\t\t+ \", " + filedName + "=\" + " + filedName
+ "\n");
}
}
sb.append("\t\t + \"]\";\n");
sb.append("\t}\n");
String code = sb.toString();
String className = pojoClass.getSimpleName();
code = code.replaceAll("\\$\\{class\\}", className);
return code;

}

private static String toLowercaseFirst(String pojoClassName) {
return pojoClassName.substring(0, 1).toLowerCase()
+ pojoClassName.substring(1);
}

interface MethodnameFilter {
boolean accept(String name);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值