粗略获取项目中出现的递归函数。
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test3 {
public static void main(String[] args) throws Exception {
String root = "I:\\Works\\workspace\\xxx";// 项目根目录
File file = new File(root);
listFiles(file);
}
/**
* 递归项目中的所有Java文件
* @param file 路径
*/
static private void listFiles(File file) {
if (file.exists()) {
if (file.isFile()) {
String absolutePath = file.getAbsolutePath();
if (absolutePath.endsWith(".java")) {
// System.out.println(absolutePath);
listMethodName(absolutePath);
}
} else {
File[] listFiles = file.listFiles();
for (File cfile : listFiles) {
if (cfile.exists()) {
if (cfile.isFile()) {
String absolutePath = cfile.getAbsolutePath();
if (absolutePath.endsWith(".java")) {
// System.out.println(absolutePath);
listMethodName(absolutePath);
}
} else {
listFiles(cfile);
}
}
}
}
}
}
/**
* 展示方法名
* @param path 文件路径
*/
static private void listMethodName(String path) {
try {
// 获取类中的内容
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
br.close();
String s = sb.toString().replaceAll("\\s+", " ");// 去掉多余空格
// 获取类中的方法名
// public void setXX(String a) {
Pattern p = Pattern.compile(" (public|private)( [^ ]+){2,3} *\\(");
Matcher m = p.matcher(s);
Pattern pp;
Matcher mm;
String method;
int count;
Set<String> set = new HashSet<>();
while (m.find()) {
method = m.group();
method = method.substring(method.lastIndexOf(" ")).replace("(", "").trim();
// 匹配方法名出现的次数
count = 0;
pp = Pattern.compile(" " + method + "\\s*\\(");
mm = pp.matcher(s);
while (mm.find()) {
count++;
}
// 打印方法名出现2次数以上的
if (count > 1) {
// 获取函数体中的内容
String methodBody = getMethodBody(s.substring(m.end()));
if (methodBody.contains(method)) {
// System.out.println(methodBody);
// System.out.println(method);
set.add(path.substring(path.lastIndexOf("\\") + 1) + " => " + method);
}
}
}
for (String met : set) {
System.out.println(met);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取函数体中的内容
* @param s 函数字符串
*/
static private String getMethodBody(String s) {
int mark = 1;
int i = s.indexOf("{") + 1;
for (; i < s.length(); i++) {
if (s.charAt(i) == '{') {
mark++;
} else if (s.charAt(i) == '}') {
mark--;
if (mark == 0) {
break;
}
}
}
return s.substring(s.indexOf("{") + 1, i);
}
}