赞
踩
大家好,我是猿码叔叔,一位 Java 语言工作者,也是一位算法学习刚入门的小学生。很久没有为大家带来干货了。
最近遇到了一个问题,大致是这样的:如果给你一个 java 方法,如何找到有哪些菜单在使用。我的第一想法是,这不很简单吗?!使用 IDEA 自带的右键 Find Usage 功能,一步一步往上溯源最终找到 Controller 中的方法,找到 requestMapping 的映射路径,然后去数据库一查便知。
目录
我所在的这个项目是一个接近15年的老项目,使用的还是 SSM 框架。前后端没有做到分离开来,耦合度极高。所以刚才那个问题的目的大致就是要将部分方法拆分出来,降低耦合度,使得后期的维护更加方便,亦或是扩展起来更加容易。
这种项目模块或方法之间耦合度高的问题,大多出现在老项目中。而仍然使用老项目的企业中国企居多。成本与安全也是阻碍老项目得到升级的两大关键问题。随着AI的兴起,这种问题的彻底解决或许能够看到一些希望,但是否有大模型专注于解决这种问题仍然需要考虑到成本和价值问题了。
除了刚才使用 IDEA 的 Find Usage 右键功能。我们或许可以调用 IDEA 的 API 也就是 Find Usage 功能,然后将项目中的所有方法串联成一个 N 叉树。对于 Controller 中的方法可以放在 Root 节点的下一层节点中。
但,IDEA 工具真的会给你提供这个 API 吗?答案是否定的,至少我搜索了很多相关内容,也没有得到一个准确的结果。或许有相关的开源组件提供这种方法溯源菜单的功能,但也都不尽如人意。
那我们能否自己写一个这样的程序呢?
这个程序实现起来其实很简单。我们只需要使用 IO 流去读取 .java 文件或者反射取出 class 中的 declaredMethods 即可。前者更开放,也更有挑战性。后者除了能取到声明方法以外,方法中的被调用方法反射做不到这一点。
IO 流我们使用 BufferedReader 一行一行地读取 .java 文件中的内容,然后根据方法的特征解析出方法与被调用方法即可。听起来是不是很简单,怎么写代码?
考虑到 Java 中代码的多变性,比如换行、注释、内部类、静态代码块、字段等等,这些都是需要我们用算法来处理的。但这么搞下去,真的可以自己写一个 JDK 了。如果你肯坚持和足够动脑,也不是不可能实现。
如果你动手能力强,你会发现刚才说的一部分要处理的内容,jdk 可以帮你解决。比如注释。在项目编译后的 target 目录下,原来的 .java 文件会被编译成 .class 文件,这些文件中原有的注释内容100%都不会被保留。此时,我们可以考虑去读取 .class 文件来进一步实现我们的计划。
当拿到 .class 文件的数据时,我傻眼了。读取到的流数据并非我们眼睛看到的数据那样,而是二进制的字节码内容,要想解析这些数据,我们得学会解读这些内容。当然现在有很多工具可以反编译字节码文件。为了不重复造轮子,我去网上找到了如下代码,可以在 java 代码中执行反编译命令,将指定目录下的 .class 文件反编译成我们能读懂的内容。
- private void decodeClassFile(File clazzFile) {
- String absPath = clazzFile.getAbsolutePath();
- try {
- String command = "javap -c " + absPath;
- Process process = runtime.exec(command);
- // 读取命令执行结果
- BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
- StringBuilder sb = new StringBuilder();
- String line;
- while ((line = reader.readLine()) != null) {
- sb.append(line).append("\n");
- }
- // 等待命令执行完成
- process.waitFor();
-
- // 获取退出值
- process.exitValue();
- reader.close();
-
- absPath = absPath.substring(absPath.indexOf("cn"));
- absPath = absPath.replace('\\', '.');
- absPath = absPath.replace(".class", ".txt");
- // 将反编译后的内容写入到指定的文件内
- writeDecodedClazzFileDown(sb.toString(), absPath);
- } catch (IOException | InterruptedException e) {
- e.printStackTrace();
- }
- }
打开反编译后的文件,你会发现方法的内容区域会有数字序列号,这些序列号其实是执行顺序的一个标识。序列号右侧的 “//” 后面会跟随描述当前行的内容类别。如果是方法,// 会写着 “Method”,如果是接口方法则是“InterfaceMethod”,如果是字段定义则是“Field”。对于其他的描述,读者有兴趣也可以去研究一下。紧随这些描述后的内容就是 java 源代码中的真实内容了。
- 46: invokevirtual #27 // Method cn/com/xxx/xxx/pojo/dev/Admin.getUserList:()Ljava/util/List;
- 97: invokeinterface #7, 3 // InterfaceMethod org/springframework/ui/Model.addAttribute:(Ljava/lang/String;Ljava/lang/Object;)Lorg/springframework/ui/Model;
编号46,是一个普通方法;编号97是一个接口方法。46 的 Method 后面我给他分为 3 个部分。
1、方法名与方法所在的包路径。
2、() 中的内容代表参数信息。这些参数信息只包含包路径与类型,没有参数名称。
3、括号后面的内容是返回值信息。
我们看到,参数内容与返回值区域路径首字符多了一个 “L” 字符。这个代表对象类型区别于 Java 自己的 8 大基本类型。 这 8 个类型的指令如下:
dataType.put('[', "[]"); // 代表数组 dataType.put('I', "int"); dataType.put('J', "long"); dataType.put('F', "float"); dataType.put('D', "double"); dataType.put('Z', "boolean"); dataType.put('B', "byte"); dataType.put('C', "char"); dataType.put('S', "short");
对于其他更多的指令,读者可以去咨询 AI。比如文心一言或者GPT。
解析方法与被调方法前我们需要注意几点:
下面是解析代码:
- public class ProjectMethodCallingTreeGraph {
-
- private final static char[] METHOD_PREFIX = {'M', 'e', 't', 'h', 'o', 'd'};
- private final static char[] INTERFACE_METHOD_PREFIX = {'I', 'n', 't', 'e', 'r', 'f'};
- private final static String TARGET_ROOT_PATH = "D:\\WORK\\xxx\\pro-info\\xxx\\xxx-graph";
-
- private static Map<Character, String> dataType = new HashMap<>();
-
- static {
- dataType.put('[', "[]");
- dataType.put('I', "int");
- dataType.put('J', "long");
- dataType.put('F', "float");
- dataType.put('D', "double");
- dataType.put('Z', "boolean");
- dataType.put('B', "byte");
- dataType.put('C', "char");
- dataType.put('S', "short");
- }
-
- public static void main(String[] args) {
- String path = "D:\\WORK\\xx\\pro-info\\xxx\\xxxx";
- ProjectMethodCallingTreeGraph p = new ProjectMethodCallingTreeGraph();
- p.readDecodedClazzFile(path);
- }
-
-
- private void readDecodedClazzFile(String path) {
- File file = new File(path);
- for (File f : file.listFiles()) {
- String method = null;
- String fName = f.getName().substring(0, f.getName().length() - 3);
- boolean mapperOrService = f.getName().endsWith("Service.txt") || f.getName().endsWith("Mapper.txt");
- LinkedHashSet<String> callMethods = new LinkedHashSet<>();
- try (BufferedReader br = new BufferedReader(new FileReader(f))) {
- String line;
- StringBuilder sb = new StringBuilder();
- while ((line = br.readLine()) != null) {
- char[] cs = line.toCharArray();
- String res = findMethodLine(cs, callMethods, mapperOrService);
- if (res != null) {
- if (method != null && method.length() > 2) {
- sb.append("----").append(fName).append(method).append("\n");
- append(sb, callMethods, fName);
- callMethods.clear();
- }
- method = res;
- }
- }
-
- writeDown(f.getName(), sb.toString());
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
- }
- }
-
- private void append(StringBuilder sb, LinkedHashSet<String> callMethods, String fName) {
- for (String m : callMethods) {
- sb.append("--------");
- if (localMethod(m)) {
- sb.append(fName);
- }
- sb.append(m).append("\n");
- }
- }
-
- private boolean localMethod(String str) {
- int n = str.length(), leftParenthesis = -1;
- for (int i = 0; i < n; ++i) {
- if (leftParenthesis == -1 && str.charAt(i) == '.') {
- return false;
- }
- if (leftParenthesis == -1 && str.charAt(i) == '(') {
- leftParenthesis = i;
- }
- }
- return true;
- }
-
- private void writeDown(String fname, String content) {
- try (BufferedWriter bw = new BufferedWriter(new FileWriter(TARGET_ROOT_PATH + "\\" + fname))) {
- bw.write(content);
- } catch (Exception e) {
- e.fillInStackTrace();
- }
- }
-
- private String findMethodLine(char[] cs, LinkedHashSet<String> calledMethods, boolean mapperOrService) {
- int x = 0, n = cs.length;
- while (x < n && cs[x] == ' ') {
- ++x;
- }
- return x == 2 ? getSpecialCharIndex(cs, mapperOrService) : (x > 4 ? findCalledMethods(cs, x, calledMethods) : null);
- }
-
- private String findCalledMethods(char[] cs, int x, LinkedHashSet<String> calledMethods) {
- // interfaceMethod
- StringBuilder sb = new StringBuilder();
- int n = cs.length;
- boolean canAppend = false, inParenthesis = false, simpleDataTypePrior = false;
- String typeMask = "";
- for (; x < n; ++x) {
- if (cs[x] == '/' && cs[x - 1] == '/') {
- if (cs[x + 2] == 'M' && compare2Arrays(cs, x + 2, METHOD_PREFIX)) {
- x += 8;
- canAppend = true;
- } else if (cs[x + 2] == 'I' && compare2Arrays(cs, x + 2, INTERFACE_METHOD_PREFIX)) {
- canAppend = true;
- x += 17;
- } else {
- return null;
- }
- continue;
- }
- if (cs[x] == '[' || (x + 1 < n && cs[x + 1] == ')' && cs[x] == ';')) {
- continue;
- }
- if (canAppend && cs[x] != ':') {
- if (cs[x] == '/') {
- sb.append('.');
- } else if (cs[x] == ';') {
- sb.append(typeMask).append(", ");
- typeMask = "";
- simpleDataTypePrior = false;
- } else {
- if (inParenthesis && cs[x - 1] == '[') {
- typeMask = "[]";
- }
- if (cs[x] == 'L' && (cs[x - 1] == '(' || cs[x - 1] == '[' || cs[x - 1] == ';')) {
- continue;
- }
- if ((cs[x - 1] == '(' || cs[x - 1] == ';' || simpleDataTypePrior || cs[x - 1] == '[') && dataType.containsKey(cs[x])) {
- simpleDataTypePrior = true;
- sb.append(dataType.get(cs[x]));
- if (cs[x - 1] == '[') {
- sb.append("[]");
- }
- if ((x + 1 < n && cs[x + 1] != ')') || (x + 1 < n && cs[x + 1] == ';' && cs[x + 2] != ')')) {
- sb.append(", ");
- }
- } else {
- sb.append(cs[x]);
- }
- }
- if (cs[x] == '(') {
- inParenthesis = true;
- }
- }
- if (cs[x] == ')') {
- break;
- }
- }
- if (sb.length() > 0) {
- calledMethods.add(sb.toString());
- }
- return null;
- }
-
- private boolean compare2Arrays(char[] a, int x, char[] b) {
- return Arrays.equals(a, x, x + b.length, b, 0, b.length);
- }
-
- private String getSpecialCharIndex(char[] cs, boolean mapperOrService) {
-
-
- int pre = 0, cnt = 0, leftParenthesis = -1;
- StringBuilder sb = new StringBuilder();
- for (int i = 2; i < cs.length; ++i) {
- if (leftParenthesis != -1) {
- sb.append(cs[i]);
- }
- if (leftParenthesis == -1 && cs[i] == ' ') {
- pre = i;
- ++cnt;
- }
- if (leftParenthesis == -1 && cs[i] == '(') {
- leftParenthesis = i;
- i = pre;
- }
- if (cs[i] == ')') {
- break;
- }
- }
- return cnt > 1 ? sb.toString() : null;
- }
- }
配置好 .class 文件的路径以及写入的目标路径后,执行代码,等待几秒后,就可以去看看写入的方法与被调方法信息了。
为了更直观的表达各方法之间的调用关系。我们可以为此创建一个 web 页面,来展现这些方法与方法之间的调用关系。由于时间有限,目前只能向读者提供方法与方法之间的调用关系,后续会丰富功能,并向大家展示。
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>方法调用关系图</title>
- <style>
- html {
- background: orange;
- }
- .container {
- margin: 0;
- padding: 0;
- text-align: center;
- flex-direction: column;
- }
- .list-box {
- margin-top: 10px;
- height: 80px;
- overflow-y: hidden;
- border: solid 5px lightgray;
- overflow-x: scroll;
- }
- .list-item {
- list-style: none;
- padding: 2px 3px;
- }
- ul {
- display: flex;
- }
- li > button:hover {
- background: black;
- color: white;
- }
- button {
- background: white;
- color: rgba(0, 0, 0, 0.6);
- padding: 4px 6px;
- border: none;
- cursor: pointer;
- border-radius: 3px;
- }
- .clicked_current {
- color: white;
- background: black;
- }
- </style>
- </head>
- <body>
- <div class="container">
- </div>
- </body>
- <script type="text/javascript">
-
- const XMLRequest = new XMLHttpRequest();
- let level = 0;
-
- window.onload = function () {
- const url = "http://localhost/methodGraph";
- request(url, 'get', false);
- XMLRequest.onreadystatechange = function () {
- if (XMLRequest.readyState === XMLHttpRequest.DONE && (XMLRequest.status === 200 || XMLRequest.status === 304)) {
- renderElements(JSON.parse(XMLRequest.responseText));
- }
- }
- XMLRequest.send(null);
- }
-
- function request(url, method, async) {
- XMLRequest.open(method, url, async);
- XMLRequest.setRequestHeader('Content-Type', 'application/json');
- }
-
- let curLevel = -1;
- function renderElements(arr) {
- const parentDom = document.querySelector(".container");
- const frag = document.createDocumentFragment();
- for (const item of arr) {
- const li = document.createElement("li");
- li.classList.add("list-item");
- const btn = document.createElement("button");
- btn.onclick = function () {
- curLevel = parseInt(this.parentNode.parentNode.classList[0].substring(5));
- const docs = document.querySelectorAll(".clicked_current");
- for (const doc of docs) {
- doc.classList.remove("clicked_current");
- }
- btn.classList.add("clicked_current");
- search(item);
- }
- btn.title = item;
- btn.textContent = getNameFromLongString(item);
- li.appendChild(btn);
- frag.append(li);
- }
- if (curLevel === level - 1) {
- if (arr.length > 0) {
- const div = document.createElement("div");
- div.classList.add("list-box");
- const ul = document.createElement("ul");
- ul.classList.add(`level${level++}`)
- ul.appendChild(frag);
- div.appendChild(ul);
- parentDom.appendChild(div);
- }
- } else {
- let rem = curLevel + 2;
- if (arr.length > 0) {
- const ulExist = document.querySelector(`.level${curLevel + 1}`);
- ulExist.innerHTML = "";
- ulExist.appendChild(frag);
- rem++;
- }
- while (parentDom.childNodes.length > rem) {
- const last = parentDom.childNodes.length;
- parentDom.removeChild(parentDom.childNodes[last - 1]);
- level--;
- }
- }
- }
-
- function getNameFromLongString(longName) {
- if (level === 0) {
- return longName.substring(longName.lastIndexOf('.') + 1);
- }
- longName = longName.substring(0, longName.indexOf('('));
- return longName.substring(longName.lastIndexOf('.') + 1);
- }
-
- function search(name) {
- const url = `http://localhost/findByName?name=${name}`;
- request(url, 'get', false);
- XMLRequest.onreadystatechange = function () {
- if (XMLRequest.readyState === XMLHttpRequest.DONE && (XMLRequest.status === 200 || XMLRequest.status === 304)) {
- renderElements(JSON.parse(XMLRequest.responseText));
- }
- }
- XMLRequest.send(null);
- }
- </script>
- </html>
- @RequestMapping("/findByName")
- @ResponseBody
- public List<String> findByName(@RequestParam(name = "name", defaultValue = "unknown") String name) {
- return projectInformationService.findByClazzName(name);
- }
- package com.example.develper.demos.service;
-
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Service;
-
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.util.*;
-
- @Service
- public class ProjectInformationServiceImpl implements ProjectInformationService{
-
- Map<String, Map<String, List<String>>> name2Clazz;
-
- // 在 properties 中配置之前保存的那个目录里
- @Value("${methodConnection.analyze.target.path}")
- private String methodConnectionPath;
-
- private void initialized() {
- if (name2Clazz != null) { return; }
- if (methodConnectionPath == null) {
- throw new IllegalArgumentException("请配置已经解析好的方法关系网络文档路径!");
- }
- name2Clazz = new HashMap<>();
- File file = new File(methodConnectionPath);
- if (!file.exists()) {
- throw new IllegalArgumentException("请配置正确的文档路径!");
- }
- loadsClazzInfo(file);
- }
-
- private void loadsClazzInfo(File file) {
- File[] files = file.listFiles();
- for (File f : files) {
- String name = f.getName().substring(0, f.getName().length() - 4);
- Map<String, List<String>> method2CalledMethods = new HashMap<>();
- name2Clazz.put(name, method2CalledMethods);
- try (BufferedReader br = new BufferedReader(new FileReader(f))) {
- String line;
- String methodName = null;
- while ((line = br.readLine()) != null) {
- String[] ret = countPlaceholder(line);
- if ("4".equals(ret[0])) {
- methodName = ret[1];
- method2CalledMethods.put(methodName, new ArrayList<>());
- } else if (methodName != null) {
- method2CalledMethods.get(methodName).add(ret[1]);
- }
- }
- } catch (Exception e) {
- e.fillInStackTrace();
- }
- }
- }
-
- private String[] countPlaceholder(String line) {
- int x = 0, cnt = 0, n = line.length();
- StringBuilder sb = new StringBuilder();
- while (x < n) {
- if (line.charAt(x) == '-') {
- ++cnt;
- } else {
- sb.append(line.charAt(x));
- }
- ++x;
- }
- String[] ret = new String[2];
- ret[0] = Integer.toString(cnt);
- ret[1] = sb.toString();
- return ret;
- }
-
- @Override
- public List<String> loadAllControllers() {
- initialized();
- List<String> ret = new ArrayList<>();
- for (String name : name2Clazz.keySet()) {
- if (name.endsWith("Controller")) {
- ret.add(name);
- }
- }
- return ret;
- }
-
- @Override
- public List<String> findByClazzName(String name) {
- // cn.com.xx.xx.common.Base58.encode(
- if (name == null || name.trim().isEmpty()) {
- return new ArrayList<>();
- }
- if (name.endsWith("Controller")) {
- return new ArrayList<>(name2Clazz.getOrDefault(name, new HashMap<>()).keySet());
- }
- char[] cs = name.toCharArray();
- StringBuilder prefix = new StringBuilder();
- StringBuilder suffix = new StringBuilder();
- int i = 0;
- while (i < cs.length && cs[i] != '(') {
- if (cs[i] == '.') {
- prefix.append(prefix.length() > 0 ? '.' : "").append(suffix);
- suffix.setLength(0);
- } else {
- suffix.append(cs[i]);
- }
- ++i;
- }
- while (i < cs.length) {
- suffix.append(cs[i++]);
- }
- char[] service = {'S', 'e', 'r', 'v', 'i', 'c', 'e'};
- int x = prefix.length() - 1, k = service.length - 1;
- while (k >= 0 && prefix.charAt(x) == service[k]) {
- --x; --k;
- }
- String clazzName = prefix.toString();
- if (k == -1) {
- x = prefix.length();
- while (prefix.charAt(x - 1) != '.') {
- --x;
- }
- prefix.insert(x, "impl.");
- clazzName = prefix.append("Impl").toString();
- name = prefix.append(".").append(suffix).toString();
- }
- Map<String, List<String>> clazz2Methods = name2Clazz.getOrDefault(clazzName, new HashMap<>());
- return clazz2Methods.getOrDefault(name, new ArrayList<>());
- }
- }
创作不易,期待读者的支持。web 页面效果不是很理想,后续会持续更新。毕竟这个功能给我平时的工作帮助挺大的。况且先前说的根据方法找菜单的功能并没有完全实现,但就目前的方向来看,一定是正确的。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。