decompile_class
Decompile Java class files to retrieve source code for analyzing dependencies and preventing AI hallucinations in generated code.
Instructions
反编译指定的Java类文件,返回Java源码
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| className | Yes | 要反编译的Java类全名,如:com.example.QueryBizOrderDO | |
| projectPath | Yes | Maven项目根目录路径 | |
| useCache | No | 是否使用缓存,默认true | |
| cfrPath | No | CFR反编译工具的jar包路径,可选 |
Implementation Reference
- Core helper method implementing the decompilation logic: handles CFR initialization, caching, JAR lookup via DependencyScanner, class file extraction from JAR using yauzl, CFR execution via child_process, and cleanup.
async decompileClass(className: string, projectPath: string, useCache: boolean = true, cfrPath?: string): Promise<string> { try { // 如果外部指定了CFR路径,则使用外部路径 if (cfrPath) { this.cfrPath = cfrPath; console.error(`使用外部指定的CFR工具路径: ${this.cfrPath}`); } else { await this.initializeCfrPath(); } // 1. 检查缓存 const cachePath = this.getCachePath(className, projectPath); if (useCache && await fs.pathExists(cachePath)) { console.error(`使用缓存的反编译结果: ${cachePath}`); return await readFile(cachePath, 'utf-8'); } // 2. 查找类对应的JAR包 console.error(`查找类 ${className} 对应的JAR包...`); // 添加超时处理 const jarPath = await Promise.race([ this.scanner.findJarForClass(className, projectPath), new Promise<null>((_, reject) => setTimeout(() => reject(new Error('查找JAR包超时')), 10000) ) ]); if (!jarPath) { throw new Error(`未找到类 ${className} 对应的JAR包,请先运行 scan_dependencies 建立类索引`); } console.error(`找到JAR包: ${jarPath}`); // 3. 从JAR包中提取.class文件 const classFilePath = await this.extractClassFile(jarPath, className); // 4. 使用CFR反编译 const sourceCode = await this.decompileWithCfr(classFilePath); // 5. 保存到缓存 if (useCache) { await fs.ensureDir(path.dirname(cachePath)); await fs.outputFile(cachePath, sourceCode, 'utf-8'); console.error(`反编译结果已缓存: ${cachePath}`); } // 6. 清理临时文件(只有在不使用缓存时才清理) if (!useCache) { try { await fs.remove(classFilePath); console.error(`清理临时文件: ${classFilePath}`); } catch (cleanupError) { console.warn(`清理临时文件失败: ${cleanupError}`); } } return sourceCode; } catch (error) { console.error(`反编译类 ${className} 失败:`, error); throw error; // 重新抛出错误,让上层处理 } }