用nat123做自己的網(wǎng)站一鍵seo提交收錄
????????大家好,我是猿碼叔叔,一位 Java 語言工作者,也是一位算法學(xué)習(xí)剛?cè)腴T的小學(xué)生。很久沒有為大家?guī)砀韶浟恕?/p>
????????最近遇到了一個問題,大致是這樣的:如果給你一個 java 方法,如何找到有哪些菜單在使用。我的第一想法是,這不很簡單嗎?!使用 IDEA 自帶的右鍵 Find Usage 功能,一步一步往上溯源最終找到 Controller 中的方法,找到 requestMapping 的映射路徑,然后去數(shù)據(jù)庫一查便知。? ? ?
目錄
一、問題真的這么簡單嗎?我們先分析一下這種問題的出現(xiàn)場景
二、有沒有更快的解決方案?
三、如何提取 Java 對象中的方法以及方法中的被調(diào)用方法
? ? ? ? IO 流讀取 .java 文件
? ? ? ? JDK 編譯后的 .class 字節(jié)碼文件
四、解讀 -javap 命令反編譯后的內(nèi)容
五、用代碼解析出類的方法與被調(diào)方法
六、讓方法與被調(diào)方法的關(guān)系可視化
一、問題真的這么簡單嗎?我們先分析一下這種問題的出現(xiàn)場景
????????我所在的這個項目是一個接近15年的老項目,使用的還是 SSM 框架。前后端沒有做到分離開來,耦合度極高。所以剛才那個問題的目的大致就是要將部分方法拆分出來,降低耦合度,使得后期的維護(hù)更加方便,亦或是擴(kuò)展起來更加容易。?
? ? ? ? 這種項目模塊或方法之間耦合度高的問題,大多出現(xiàn)在老項目中。而仍然使用老項目的企業(yè)中國企居多。成本與安全也是阻礙老項目得到升級的兩大關(guān)鍵問題。隨著AI的興起,這種問題的徹底解決或許能夠看到一些希望,但是否有大模型專注于解決這種問題仍然需要考慮到成本和價值問題了。
二、有沒有更快的解決方案?
? ? ? ? 除了剛才使用 IDEA 的 Find?Usage 右鍵功能。我們或許可以調(diào)用 IDEA 的 API 也就是 Find Usage 功能,然后將項目中的所有方法串聯(lián)成一個 N 叉樹。對于?Controller 中的方法可以放在 Root 節(jié)點的下一層節(jié)點中。
? ? ? ? 但,IDEA 工具真的會給你提供這個 API 嗎?答案是否定的,至少我搜索了很多相關(guān)內(nèi)容,也沒有得到一個準(zhǔn)確的結(jié)果?;蛟S有相關(guān)的開源組件提供這種方法溯源菜單的功能,但也都不盡如人意。
? ? ? ? 那我們能否自己寫一個這樣的程序呢?
三、如何提取 Java 對象中的方法以及方法中的被調(diào)用方法
? ? ? ? 這個程序?qū)崿F(xiàn)起來其實很簡單。我們只需要使用 IO 流去讀取 .java 文件或者反射取出 class 中的 declaredMethods 即可。前者更開放,也更有挑戰(zhàn)性。后者除了能取到聲明方法以外,方法中的被調(diào)用方法反射做不到這一點。
? ? ? ? IO 流讀取 .java 文件
? ? ? ? IO 流我們使用 BufferedReader 一行一行地讀取 .java 文件中的內(nèi)容,然后根據(jù)方法的特征解析出方法與被調(diào)用方法即可。聽起來是不是很簡單,怎么寫代碼?
? ? ? ? 考慮到 Java 中代碼的多變性,比如換行、注釋、內(nèi)部類、靜態(tài)代碼塊、字段等等,這些都是需要我們用算法來處理的。但這么搞下去,真的可以自己寫一個 JDK 了。如果你肯堅持和足夠動腦,也不是不可能實現(xiàn)。
? ? ? ? JDK 編譯后的 .class 字節(jié)碼文件
? ? ? ? 如果你動手能力強(qiáng),你會發(fā)現(xiàn)剛才說的一部分要處理的內(nèi)容,jdk 可以幫你解決。比如注釋。在項目編譯后的 target 目錄下,原來的 .java 文件會被編譯成 .class 文件,這些文件中原有的注釋內(nèi)容100%都不會被保留。此時,我們可以考慮去讀取 .class 文件來進(jìn)一步實現(xiàn)我們的計劃。
? ? ? ? 當(dāng)拿到 .class 文件的數(shù)據(jù)時,我傻眼了。讀取到的流數(shù)據(jù)并非我們眼睛看到的數(shù)據(jù)那樣,而是二進(jìn)制的字節(jié)碼內(nèi)容,要想解析這些數(shù)據(jù),我們得學(xué)會解讀這些內(nèi)容。當(dāng)然現(xiàn)在有很多工具可以反編譯字節(jié)碼文件。為了不重復(fù)造輪子,我去網(wǎng)上找到了如下代碼,可以在 java 代碼中執(zhí)行反編譯命令,將指定目錄下的 .class 文件反編譯成我們能讀懂的內(nèi)容。
private void decodeClassFile(File clazzFile) {String absPath = clazzFile.getAbsolutePath();try {String command = "javap -c " + absPath;Process process = runtime.exec(command);// 讀取命令執(zhí)行結(jié)果BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));StringBuilder sb = new StringBuilder();String line;while ((line = reader.readLine()) != null) {sb.append(line).append("\n");}// 等待命令執(zhí)行完成process.waitFor();// 獲取退出值process.exitValue();reader.close();absPath = absPath.substring(absPath.indexOf("cn"));absPath = absPath.replace('\\', '.');absPath = absPath.replace(".class", ".txt");// 將反編譯后的內(nèi)容寫入到指定的文件內(nèi)writeDecodedClazzFileDown(sb.toString(), absPath);} catch (IOException | InterruptedException e) {e.printStackTrace();}}
四、解讀 -javap 命令反編譯后的內(nèi)容
? ? ? ? 打開反編譯后的文件,你會發(fā)現(xiàn)方法的內(nèi)容區(qū)域會有數(shù)字序列號,這些序列號其實是執(zhí)行順序的一個標(biāo)識。序列號右側(cè)的 “//” 后面會跟隨描述當(dāng)前行的內(nèi)容類別。如果是方法,// 會寫著? “Method”,如果是接口方法則是“InterfaceMethod”,如果是字段定義則是“Field”。對于其他的描述,讀者有興趣也可以去研究一下。緊隨這些描述后的內(nèi)容就是 java 源代碼中的真實內(nèi)容了。
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、() 中的內(nèi)容代表參數(shù)信息。這些參數(shù)信息只包含包路徑與類型,沒有參數(shù)名稱。
3、括號后面的內(nèi)容是返回值信息。
? ? ? ? 我們看到,參數(shù)內(nèi)容與返回值區(qū)域路徑首字符多了一個 “L” 字符。這個代表對象類型區(qū)別于 Java 自己的 8 大基本類型。?這 8 個類型的指令如下:
dataType.put('[', "[]"); // 代表數(shù)組 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。
五、用代碼解析出類的方法與被調(diào)方法
? ? ? ? 解析方法與被調(diào)方法前我們需要注意幾點:
- Service 方法與 ServiceImpl 實現(xiàn)類的方法轉(zhuǎn)換。在 Service 方法中的方法體是沒有內(nèi)容的,其內(nèi)容會在他的實現(xiàn)類對應(yīng)的方法體里。這時候你應(yīng)該知道我要強(qiáng)調(diào)的是什么了。
- 方法與被調(diào)方法的參數(shù)信息在反編譯文件里的內(nèi)容是不同的,比如 double 類型與 int 類型同時存在時,你看到的是 “DI”,如果前者是數(shù)組,你看到的是“[DI”。所以為了在拿到被調(diào)方法時能夠準(zhǔn)確找到下一個節(jié)點,我們必須對這些內(nèi)容進(jìn)行還原
- 如上一條所說,我們解析出方法與被調(diào)方法的目的是能夠準(zhǔn)確的通過方法找到有哪些被調(diào)方法,拿到被調(diào)方法,能夠準(zhǔn)確找到被調(diào)方法中的被調(diào)方法。這是一個 N-ary 樹的遍歷思想,直到找不到為止。
- 當(dāng)前類的自有方法互相調(diào)用,需要拼接其包路徑。這是為了統(tǒng)一管理。
- 解析后的內(nèi)容,在存放時應(yīng)當(dāng)有一個便于處理的格式。比如一級方法名前面沒有空格,而二級的被調(diào)方法則應(yīng)當(dāng)在前面加上四個“-”字符,這樣可以明確他們之間的關(guān)系。
? ? ? 下面是解析代碼:
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) {// interfaceMethodStringBuilder 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 文件的路徑以及寫入的目標(biāo)路徑后,執(zhí)行代碼,等待幾秒后,就可以去看看寫入的方法與被調(diào)方法信息了。
六、讓方法與被調(diào)方法的關(guān)系可視化
? ? ? ? 為了更直觀的表達(dá)各方法之間的調(diào)用關(guān)系。我們可以為此創(chuàng)建一個 web 頁面,來展現(xiàn)這些方法與方法之間的調(diào)用關(guān)系。由于時間有限,目前只能向讀者提供方法與方法之間的調(diào)用關(guān)系,后續(xù)會豐富功能,并向大家展示。
- web 頁面
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>方法調(diào)用關(guān)系圖</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>
- controller
@RequestMapping("/findByName")@ResponseBodypublic List<String> findByName(@RequestParam(name = "name", defaultValue = "unknown") String name) {return projectInformationService.findByClazzName(name);}
- 實現(xiàn)類
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("請配置已經(jīng)解析好的方法關(guān)系網(wǎng)絡(luò)文檔路徑!");}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;}@Overridepublic List<String> loadAllControllers() {initialized();List<String> ret = new ArrayList<>();for (String name : name2Clazz.keySet()) {if (name.endsWith("Controller")) {ret.add(name);}}return ret;}@Overridepublic 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<>());}
}
七、結(jié)語
? ? ? ? 創(chuàng)作不易,期待讀者的支持。web 頁面效果不是很理想,后續(xù)會持續(xù)更新。畢竟這個功能給我平時的工作幫助挺大的。況且先前說的根據(jù)方法找菜單的功能并沒有完全實現(xiàn),但就目前的方向來看,一定是正確的。