├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── decompiler │ │ ├── Decompiler.java │ │ ├── Main.java │ │ ├── config │ │ ├── DecompilerConfig.java │ │ ├── OptionsBuilder.java │ │ └── VineflowerOptions.java │ │ ├── exception │ │ ├── ConfigException.java │ │ ├── DecompileException.java │ │ └── FileProcessException.java │ │ ├── model │ │ └── DecompileJob.java │ │ ├── task │ │ ├── DecompileResult.java │ │ ├── DecompileTask.java │ │ └── TaskManager.java │ │ └── util │ │ ├── FileUtil.java │ │ ├── JarUtils.java │ │ └── VineDecompiler.java └── resources │ └── logback.xml └── test └── java └── Test.java /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Decompiler 2 | 一个基于 Vineflower 引擎的多线程 Java 批量反编译工具,支持快速处理大量的 class 文件和 JAR 文件。 3 | 4 | ## 功能特点 5 | 6 | - 多线程处理:利用多线程处理反编译以提高效率 7 | - 灵活配置:支持配置 Vineflower 反编译引擎的高级选项 8 | - 批量处理:一次性处理成千上万的类文件 9 | - 自动清理:可选择反编译成功后删除原始 class 文件 10 | 11 | ## 使用方法 12 | 13 | 在 test 目录下有使用样例的代码 14 | ```java 15 | DecompilerConfig config = new DecompilerConfig.Builder() 16 | .inputPath("/xxxx/code") 17 | .outputPath("/xxxx/output") 18 | .threadCount(8) 19 | .deleteClassFiles(true) 20 | .build(); 21 | OptionsBuilder optionsBuilder = new OptionsBuilder(); 22 | Map vineflowerOptions = optionsBuilder.build(); 23 | Decompiler decompiler = new Decompiler(config, vineflowerOptions); 24 | long startTime = System.currentTimeMillis(); 25 | decompiler.execute(); 26 | 27 | long endTime = System.currentTimeMillis(); 28 | double totalTime = (endTime - startTime) / 1000.0; 29 | logger.info("总耗时: " + totalTime + " 秒"); 30 | ``` 31 | 32 | ## 测试 33 | 混合场景下(JAR 和 class 放在一个目录中)共 43553 个文件,开启 8 线程用了 391.875 秒 34 | ```text 35 | 2025-04-27 22:26:57.191 INFO 文件总数:43552 36 | 2025-04-27 22:26:57.191 INFO 已成功反编译:43552 37 | 2025-04-27 22:26:57.191 INFO 失败:0 38 | 2025-04-27 22:26:57.192 INFO 总耗时: 391.875 秒 39 | ``` 40 | 41 | ## 存在的问题 42 | 43 | 在 vineflower 反编译 class 文件的时候会有下面的情况: 44 | ```test 45 | xxx_1.class -> xxx.java 46 | ``` 47 | 会丢失下划线以及数字,这个 bug 目前还没有修复,如果有师傅们有解决方案可以提交 PR 48 | 49 | ## 一起完善 50 | 作者只是为了在学习和研究中方便操作才写了这个工具,如果存在 bug 和不合理的地方欢迎指正 -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.decompiler 8 | JavaDecompiler 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 17 13 | 17 14 | UTF-8 15 | 16 | 17 | 18 | 19 | org.vineflower 20 | vineflower 21 | 1.11.1 22 | 23 | 24 | 25 | commons-io 26 | commons-io 27 | 2.15.1 28 | 29 | 30 | 31 | commons-cli 32 | commons-cli 33 | 1.6.0 34 | 35 | 36 | 37 | org.slf4j 38 | slf4j-api 39 | 2.0.11 40 | 41 | 42 | ch.qos.logback 43 | logback-classic 44 | 1.5.13 45 | 46 | 47 | 48 | 49 | JavaDecompiler 50 | 51 | 52 | 53 | org.apache.maven.plugins 54 | maven-compiler-plugin 55 | 3.11.0 56 | 57 | ${maven.compiler.source} 58 | ${maven.compiler.target} 59 | ${project.build.sourceEncoding} 60 | 61 | 62 | 63 | 64 | org.apache.maven.plugins 65 | maven-assembly-plugin 66 | 3.6.0 67 | 68 | 69 | 70 | com.decompiler.Main 71 | 72 | 73 | 74 | jar-with-dependencies 75 | 76 | JavaDecompiler 77 | false 78 | 79 | 80 | 81 | make-assembly 82 | package 83 | 84 | single 85 | 86 | 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /src/main/java/com/decompiler/Decompiler.java: -------------------------------------------------------------------------------- 1 | package com.decompiler; 2 | 3 | import com.decompiler.config.DecompilerConfig; 4 | import com.decompiler.model.DecompileJob; 5 | import com.decompiler.task.DecompileResult; 6 | import com.decompiler.task.DecompileTask; 7 | import com.decompiler.task.TaskManager; 8 | import com.decompiler.util.FileUtil; 9 | import com.decompiler.util.JarUtils; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | import java.io.File; 14 | import java.io.IOException; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | import java.util.Map; 18 | import java.util.concurrent.atomic.AtomicInteger; 19 | 20 | public class Decompiler { 21 | private static final Logger logger = LoggerFactory.getLogger(Decompiler.class); 22 | 23 | private final DecompilerConfig config; 24 | private final Map vineflowerOptions; 25 | private final TaskManager taskManager; 26 | private final AtomicInteger successCount = new AtomicInteger(0); 27 | private final AtomicInteger failureCount = new AtomicInteger(0); 28 | 29 | public Decompiler(DecompilerConfig config, Map vineflowerOptions) { 30 | this.config = config; 31 | this.vineflowerOptions = vineflowerOptions; 32 | this.taskManager = new TaskManager(config.getThreadCount()); 33 | } 34 | 35 | public void execute() throws IOException { 36 | logger.info("使用 {} 个线程启动反编译", config.getThreadCount()); 37 | logger.info("输入目录:{}", config.getInputPath()); 38 | logger.info("输出目录: {}", config.getOutputPath()); 39 | 40 | // 准备需要反编译的文件 41 | List jobs = prepareDecompileJobs(); 42 | 43 | logger.info("共找到 {} 个等待反编译的文件", jobs.size()); 44 | 45 | if (jobs.isEmpty()) { 46 | logger.warn("没有找到可反编译的文件"); 47 | return; 48 | } 49 | 50 | // 执行反编译任务 51 | List results = taskManager.processTasks(jobs, 52 | (job) -> new DecompileTask(job, config, vineflowerOptions), 53 | this::processResult); 54 | 55 | // 输出统计信息 56 | printStats(); 57 | } 58 | 59 | private void processResult(DecompileResult result) { 60 | if (result.isSuccess()) { 61 | successCount.incrementAndGet(); 62 | } else { 63 | failureCount.incrementAndGet(); 64 | logger.warn("反编译失败: {}, 错误: {}", 65 | result.getJob().getSourceFile().getName(), 66 | result.getErrorMessage()); 67 | } 68 | } 69 | 70 | private List prepareDecompileJobs() throws IOException { 71 | File inputFile = new File(config.getInputPath()); 72 | 73 | // 如果是目录 74 | if (inputFile.isDirectory()) { 75 | return FileUtil.processDirectory(inputFile, config.getOutputPath(), taskManager); 76 | } 77 | // 如果是 JAR 78 | else if (JarUtils.isJarFile(inputFile)) { 79 | return FileUtil.processJarFile(inputFile, config.getOutputPath()); 80 | } 81 | // 如果是单个 class 文件 82 | else if (inputFile.getName().toLowerCase().endsWith(".class")) { 83 | return FileUtil.processClassFile(inputFile, config.getOutputPath()); 84 | } else { 85 | throw new IllegalArgumentException("输入必须是.class文件、.jar文件或目录"); 86 | } 87 | } 88 | 89 | /** 90 | * 打印反编译统计信息 91 | */ 92 | private void printStats() { 93 | int total = successCount.get() + failureCount.get(); 94 | logger.info("反编译已完成"); 95 | logger.info("文件总数:{}", total); 96 | logger.info("已成功反编译:{}", successCount.get()); 97 | logger.info("失败:{}", failureCount.get()); 98 | 99 | } 100 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/Main.java: -------------------------------------------------------------------------------- 1 | package com.decompiler; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | public class Main { 7 | private static final Logger logger = LoggerFactory.getLogger(Main.class); 8 | // TODO: CIL 解析 9 | public static void main(String[] args) { 10 | 11 | } 12 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/config/DecompilerConfig.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.config; 2 | 3 | public class DecompilerConfig { 4 | private final String inputPath; 5 | private final String outputPath; 6 | private final int threadCount; 7 | private final boolean deleteClassFiles; 8 | 9 | private DecompilerConfig(Builder builder) { 10 | this.inputPath = builder.inputPath; 11 | this.outputPath = builder.outputPath; 12 | this.threadCount = builder.threadCount; 13 | this.deleteClassFiles = builder.deleteClassFiles; 14 | } 15 | 16 | public String getInputPath() { 17 | return inputPath; 18 | } 19 | 20 | public String getOutputPath() { 21 | return outputPath; 22 | } 23 | 24 | public int getThreadCount() { 25 | return threadCount; 26 | } 27 | 28 | public boolean isDeleteClassFiles() { 29 | return deleteClassFiles; 30 | } 31 | 32 | public static class Builder { 33 | private String inputPath; 34 | private String outputPath; 35 | private int threadCount = Runtime.getRuntime().availableProcessors(); 36 | private boolean deleteClassFiles = false; // 默认不删除class文件 37 | 38 | public Builder inputPath(String inputPath) { 39 | this.inputPath = inputPath; 40 | return this; 41 | } 42 | 43 | public Builder outputPath(String outputPath) { 44 | this.outputPath = outputPath; 45 | return this; 46 | } 47 | 48 | public Builder threadCount(int threadCount) { 49 | this.threadCount = threadCount <= 0 ? 50 | Runtime.getRuntime().availableProcessors() : threadCount; 51 | return this; 52 | } 53 | 54 | public Builder deleteClassFiles(boolean deleteClassFiles) { 55 | this.deleteClassFiles = deleteClassFiles; 56 | return this; 57 | } 58 | 59 | public DecompilerConfig build() { 60 | return new DecompilerConfig(this); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/config/OptionsBuilder.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.config; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * 构建Vineflower反编译器选项的构建器 8 | */ 9 | public class OptionsBuilder { 10 | private final Map options; 11 | 12 | public OptionsBuilder() { 13 | this.options = VineflowerOptions.loadDefaultOptions(); 14 | } 15 | 16 | /** 17 | * 添加自定义选项 18 | */ 19 | public OptionsBuilder withOption(String key, String value) { 20 | options.put(key, value); 21 | return this; 22 | } 23 | 24 | /** 25 | * 启用泛型反编译 26 | */ 27 | public OptionsBuilder withGenerics(boolean enable) { 28 | options.put(VineflowerOptions.DGS, enable ? "1" : "0"); 29 | return this; 30 | } 31 | 32 | /** 33 | * 启用内部类反编译 34 | */ 35 | public OptionsBuilder withInnerClasses(boolean enable) { 36 | options.put(VineflowerOptions.DIN, enable ? "1" : "0"); 37 | return this; 38 | } 39 | 40 | /** 41 | * 启用断言反编译 42 | */ 43 | public OptionsBuilder withAssertions(boolean enable) { 44 | options.put(VineflowerOptions.DAS, enable ? "1" : "0"); 45 | return this; 46 | } 47 | 48 | /** 49 | * 启用枚举反编译 50 | */ 51 | public OptionsBuilder withEnums(boolean enable) { 52 | options.put(VineflowerOptions.DEN, enable ? "1" : "0"); 53 | return this; 54 | } 55 | 56 | /** 57 | * 启用预览特性反编译 58 | */ 59 | public OptionsBuilder withPreviewFeatures(boolean enable) { 60 | options.put(VineflowerOptions.DPR, enable ? "1" : "0"); 61 | return this; 62 | } 63 | 64 | /** 65 | * 启用switch表达式反编译 66 | */ 67 | public OptionsBuilder withSwitchExpressions(boolean enable) { 68 | options.put(VineflowerOptions.SWE, enable ? "1" : "0"); 69 | return this; 70 | } 71 | 72 | /** 73 | * 启用模式匹配 74 | */ 75 | public OptionsBuilder withPatternMatching(boolean enable) { 76 | options.put(VineflowerOptions.PAM, enable ? "1" : "0"); 77 | return this; 78 | } 79 | 80 | /** 81 | * 使用本地变量表名称 82 | */ 83 | public OptionsBuilder withLocalVarNames(boolean enable) { 84 | options.put(VineflowerOptions.UDV, enable ? "1" : "0"); 85 | return this; 86 | } 87 | 88 | /** 89 | * 使用方法参数名 90 | */ 91 | public OptionsBuilder withMethodParams(boolean enable) { 92 | options.put(VineflowerOptions.UMP, enable ? "1" : "0"); 93 | return this; 94 | } 95 | 96 | /** 97 | * 移除空的try-catch块 98 | */ 99 | public OptionsBuilder withRemoveEmptyTryCatch(boolean enable) { 100 | options.put(VineflowerOptions.RER, enable ? "1" : "0"); 101 | return this; 102 | } 103 | 104 | /** 105 | * 隐藏空的super()调用 106 | */ 107 | public OptionsBuilder withHideEmptySuper(boolean enable) { 108 | options.put(VineflowerOptions.HES, enable ? "1" : "0"); 109 | return this; 110 | } 111 | 112 | /** 113 | * 隐藏默认构造函数 114 | */ 115 | public OptionsBuilder withHideDefaultConstructor(boolean enable) { 116 | options.put(VineflowerOptions.HDC, enable ? "1" : "0"); 117 | return this; 118 | } 119 | 120 | /** 121 | * 设置线程数 122 | */ 123 | public OptionsBuilder withThreads(int threadCount) { 124 | if (threadCount > 0) { 125 | options.put(VineflowerOptions.THR, String.valueOf(threadCount)); 126 | } 127 | return this; 128 | } 129 | 130 | /** 131 | * 设置缩进字符串 132 | */ 133 | public OptionsBuilder withIndent(String indentString) { 134 | options.put(VineflowerOptions.IND, indentString); 135 | return this; 136 | } 137 | 138 | /** 139 | * 构建最终的选项映射 140 | */ 141 | public Map build() { 142 | return new HashMap<>(options); 143 | } 144 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/config/VineflowerOptions.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.config; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.Properties; 11 | 12 | // 这里只使用了部分的选项,如果有更多需要可以参考 https://github.com/Vineflower/vineflower/blob/master/src/org/jetbrains/java/decompiler/main/extern/IFernflowerPreferences.java 加入 13 | public class VineflowerOptions { 14 | private static final Logger logger = LoggerFactory.getLogger(VineflowerOptions.class); 15 | 16 | // 核心反编译选项 17 | public static final String DIN = "din"; // 反编译内部类 18 | public static final String DGS = "dgs"; // 反编译泛型 19 | public static final String DAS = "das"; // 反编译断言 20 | public static final String DEN = "den"; // 反编译枚举 21 | public static final String DPR = "dpr"; // 反编译预览特性 22 | public static final String SWE = "swe"; // 反编译Switch表达式 23 | public static final String PAM = "pam"; // 模式匹配 24 | 25 | // 代码质量选项 26 | public static final String UDV = "udv"; // 使用LVT名称 27 | public static final String UMP = "ump"; // 使用方法参数名 28 | public static final String RER = "rer"; // 移除空的try-catch块 29 | public static final String HES = "hes"; // 隐藏空的super() 30 | public static final String HDC = "hdc"; // 隐藏默认构造函数 31 | 32 | // 格式化选项 33 | public static final String THR = "thr"; // 线程数 34 | public static final String IND = "ind"; // 缩进字符串 35 | 36 | // 加载默认选项 37 | public static Map loadDefaultOptions() { 38 | Map options = new HashMap<>(); 39 | Properties properties = new Properties(); 40 | 41 | try (InputStream in = VineflowerOptions.class.getClassLoader() 42 | .getResourceAsStream("default-options.properties")) { 43 | if (in != null) { 44 | properties.load(in); 45 | for (String key : properties.stringPropertyNames()) { 46 | options.put(key, properties.getProperty(key)); 47 | } 48 | } 49 | } catch (IOException e) { 50 | logger.warn("Failed to load default options. Using built-in defaults.", e); 51 | // 设置核心选项默认值 52 | options.put(DIN, "1"); // 默认反编译内部类 53 | options.put(DGS, "1"); // 默认反编译泛型 54 | options.put(DAS, "1"); // 默认反编译断言 55 | options.put(DEN, "1"); // 默认反编译枚举 56 | options.put(DPR, "1"); // 默认反编译预览特性 57 | options.put(SWE, "1"); // 默认反编译Switch表达式 58 | options.put(PAM, "1"); // 默认启用模式匹配 59 | 60 | // 代码质量选项默认值 61 | options.put(UDV, "1"); // 默认使用LVT名称 62 | options.put(UMP, "1"); // 默认使用方法参数名 63 | options.put(RER, "1"); // 默认移除空的try-catch块 64 | options.put(HES, "1"); // 默认隐藏空的super() 65 | options.put(HDC, "1"); // 默认隐藏默认构造函数 66 | 67 | // 格式化选项默认值 68 | // 默认使用所有可用处理器 69 | options.put(THR, String.valueOf(Runtime.getRuntime().availableProcessors())); 70 | // 默认缩进3个空格 71 | options.put(IND, " "); 72 | } 73 | 74 | return options; 75 | } 76 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/exception/ConfigException.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.exception; 2 | 3 | /** 4 | * 配置相关异常,如无效的参数、缺少必要设置等 5 | */ 6 | public class ConfigException extends Exception { 7 | 8 | public ConfigException(String message) { 9 | super(message); 10 | } 11 | 12 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/exception/DecompileException.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.exception; 2 | 3 | /** 4 | * 反编译过程中发生的异常 5 | */ 6 | public class DecompileException extends Exception { 7 | 8 | public DecompileException(String message) { 9 | super(message); 10 | } 11 | 12 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/exception/FileProcessException.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.exception; 2 | 3 | /** 4 | * 文件处理异常,包括文件读写、解析等操作中出现的错误 5 | */ 6 | public class FileProcessException extends Exception { 7 | 8 | public FileProcessException(String message) { 9 | super(message); 10 | } 11 | 12 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/model/DecompileJob.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.model; 2 | 3 | import java.io.File; 4 | 5 | /** 6 | * 表示单个反编译任务 7 | */ 8 | public class DecompileJob { 9 | private final File sourceFile; 10 | private final String targetPath; 11 | private final String relativePath; 12 | 13 | public DecompileJob(File sourceFile, String targetPath, String relativePath) { 14 | this.sourceFile = sourceFile; 15 | this.targetPath = targetPath; 16 | this.relativePath = relativePath; 17 | } 18 | 19 | public File getSourceFile() { 20 | return sourceFile; 21 | } 22 | 23 | public String getTargetPath() { 24 | return targetPath; 25 | } 26 | 27 | public String getRelativePath() { 28 | return relativePath; 29 | } 30 | 31 | @Override 32 | public String toString() { 33 | return "DecompileJob{" + 34 | "sourceFile=" + sourceFile + 35 | ", targetPath='" + targetPath + '\'' + 36 | ", relativePath='" + relativePath + '\'' + 37 | '}'; 38 | } 39 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/task/DecompileResult.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.task; 2 | 3 | import com.decompiler.model.DecompileJob; 4 | 5 | public class DecompileResult { 6 | private final DecompileJob job; 7 | private final boolean success; 8 | private final String errorMessage; 9 | private final String outputPath; 10 | 11 | public DecompileResult(DecompileJob job, boolean success, String errorMessage, String outputPath) { 12 | this.job = job; 13 | this.success = success; 14 | this.errorMessage = errorMessage; 15 | this.outputPath = outputPath; 16 | } 17 | 18 | public DecompileJob getJob() { 19 | return job; 20 | } 21 | 22 | public boolean isSuccess() { 23 | return success; 24 | } 25 | 26 | public String getErrorMessage() { 27 | return errorMessage; 28 | } 29 | 30 | public String getOutputPath() { 31 | return outputPath; 32 | } 33 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/task/DecompileTask.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.task; 2 | 3 | import com.decompiler.config.DecompilerConfig; 4 | import com.decompiler.exception.DecompileException; 5 | import com.decompiler.model.DecompileJob; 6 | import com.decompiler.util.VineDecompiler; 7 | import org.apache.commons.io.FileUtils; 8 | import org.jetbrains.java.decompiler.main.decompiler.PrintStreamLogger; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | import java.io.File; 13 | import java.io.OutputStream; 14 | import java.io.PrintStream; 15 | import java.util.Map; 16 | import java.util.concurrent.Callable; 17 | 18 | public class DecompileTask implements Callable { 19 | private static final Logger logger = LoggerFactory.getLogger(DecompileTask.class); 20 | 21 | private final DecompileJob job; 22 | private final DecompilerConfig config; 23 | private final Map options; 24 | 25 | public DecompileTask(DecompileJob job, DecompilerConfig config, Map options) { 26 | this.job = job; 27 | this.config = config; 28 | this.options = options; 29 | } 30 | 31 | @Override 32 | public DecompileResult call() { 33 | try { 34 | File classFile = job.getSourceFile(); 35 | String outputDirPath = job.getTargetPath(); 36 | 37 | // 输出目录是job中指定的目标目录 38 | File outputDir = new File(outputDirPath); 39 | FileUtils.forceMkdir(outputDir); 40 | 41 | logger.debug("反编译: {} 到 {}", classFile.getAbsolutePath(), outputDir.getAbsolutePath()); 42 | 43 | // 验证源文件存在且可读 44 | if (!classFile.exists() || !classFile.canRead()) { 45 | throw new DecompileException("源文件不存在或无法读取: " + classFile.getAbsolutePath()); 46 | } 47 | 48 | // 获取class文件基础名称(用于后续验证) 49 | String className = classFile.getName(); 50 | String baseName = className.toLowerCase().endsWith(".class") 51 | ? className.substring(0, className.length() - 6) 52 | : className; 53 | 54 | // 特殊处理含有下划线和数字的文件名(可能是内部类或生成类,这里是 vineflower bug貌似,如果是这样的文件反编译结果就会这样: TextBuilder_3.class -> TextBuilder.java) 55 | String baseNameWithoutNumber = baseName; 56 | if (baseName.contains("_")) { 57 | // 尝试去掉数字后缀,如 TextBuilder_3 -> TextBuilder 58 | int lastUnderscoreIndex = baseName.lastIndexOf("_"); 59 | if (lastUnderscoreIndex > 0 && lastUnderscoreIndex < baseName.length() - 1) { 60 | String possibleNumber = baseName.substring(lastUnderscoreIndex + 1); 61 | if (possibleNumber.matches("\\d+")) { 62 | baseNameWithoutNumber = baseName.substring(0, lastUnderscoreIndex); 63 | } 64 | } 65 | } 66 | 67 | // 记录反编译前目录中的Java文件 68 | int javaFileCountBefore = countJavaFiles(outputDir); 69 | 70 | // 创建一个不输出任何内容的日志记录器 71 | PrintStreamLogger decompilerLogger = new PrintStreamLogger(new PrintStream(OutputStream.nullOutputStream())); 72 | 73 | // 创建VineDecompiler实例并配置 74 | VineDecompiler decompiler = new VineDecompiler(outputDir, options, decompilerLogger); 75 | 76 | decompiler.addSource(classFile); 77 | 78 | logger.info("正在反编译: {}", classFile.getName()); 79 | decompiler.decompileContext(); 80 | logger.info("反编译完成: {}", classFile.getName()); 81 | 82 | // 记录反编译后目录中的Java文件 83 | int javaFileCountAfter = countJavaFiles(outputDir); 84 | 85 | // 检查是否有新生成的Java文件 86 | if (javaFileCountAfter > javaFileCountBefore) { 87 | File[] newJavaFiles = findNewJavaFiles(outputDir, baseNameWithoutNumber); 88 | 89 | if (newJavaFiles.length > 0) { 90 | logger.info("Java文件已生成:{}", newJavaFiles[0].getAbsolutePath()); 91 | 92 | // 如果配置了删除class文件 93 | if (config.isDeleteClassFiles()) { 94 | FileUtils.deleteQuietly(classFile); 95 | logger.debug("已删除class文件: {}", classFile.getAbsolutePath()); 96 | } 97 | 98 | return new DecompileResult(job, true, null, outputDir.getAbsolutePath()); 99 | } 100 | } 101 | 102 | // 直接检查可能的Java文件名 103 | File[] possibleJavaFiles = { 104 | new File(outputDir, baseName + ".java"), // 完全匹配 105 | new File(outputDir, baseNameWithoutNumber + ".java"), // 去掉数字后缀 106 | new File(outputDir, baseName.replace('$', '_') + ".java") // 内部类替换 107 | }; 108 | 109 | for (File javaFile : possibleJavaFiles) { 110 | if (javaFile.exists() && javaFile.length() > 0) { 111 | logger.info("Java文件已生成:{}", javaFile.getAbsolutePath()); 112 | 113 | // 如果配置了删除class文件 114 | if (config.isDeleteClassFiles()) { 115 | FileUtils.deleteQuietly(classFile); 116 | logger.debug("已删除class文件: {}", classFile.getAbsolutePath()); 117 | } 118 | 119 | return new DecompileResult(job, true, null, outputDir.getAbsolutePath()); 120 | } 121 | } 122 | 123 | // 未找到生成的Java文件,降级策略:接受目录中任何新的 Java 文件 124 | File[] allJavaFilesAfter = outputDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".java")); 125 | if (allJavaFilesAfter != null && allJavaFilesAfter.length > javaFileCountBefore) { 126 | // 找到了至少一个新的Java文件,认为反编译成功 127 | logger.info("反编译后发现新的Java文件,假定成功"); 128 | 129 | // 如果配置了删除class文件 130 | if (config.isDeleteClassFiles()) { 131 | FileUtils.deleteQuietly(classFile); 132 | logger.debug("已删除class文件: {}", classFile.getAbsolutePath()); 133 | } 134 | 135 | return new DecompileResult(job, true, null, outputDir.getAbsolutePath()); 136 | } 137 | 138 | // 找不到任何生成的Java文件 139 | logger.warn("未找到预期的Java文件,class文件: {}, 输出目录: {}", 140 | classFile.getName(), outputDir.getAbsolutePath()); 141 | return new DecompileResult(job, false, "未生成Java文件", outputDir.getAbsolutePath()); 142 | 143 | } catch (Exception e) { 144 | logger.error("反编译失败: " + job.getSourceFile().getAbsolutePath(), e); 145 | return new DecompileResult(job, false, e.getMessage(), null); 146 | } 147 | } 148 | 149 | /** 150 | * 计算目录中Java文件的数量 151 | */ 152 | private int countJavaFiles(File directory) { 153 | File[] javaFiles = directory.listFiles((dir, name) -> name.toLowerCase().endsWith(".java")); 154 | return javaFiles != null ? javaFiles.length : 0; 155 | } 156 | 157 | /** 158 | * 查找与基础名称匹配的Java文件 159 | */ 160 | private File[] findNewJavaFiles(File directory, String baseNamePattern) { 161 | File[] files = directory.listFiles((dir, name) -> { 162 | if (!name.toLowerCase().endsWith(".java")) { 163 | return false; 164 | } 165 | 166 | String javaBaseName = name.substring(0, name.length() - 5); 167 | return javaBaseName.equals(baseNamePattern) || // 完全匹配 168 | javaBaseName.startsWith(baseNamePattern) || // 前缀匹配 169 | javaBaseName.contains(baseNamePattern); // 包含匹配 170 | }); 171 | 172 | return files != null ? files : new File[0]; 173 | } 174 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/task/TaskManager.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.task; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.concurrent.*; 9 | import java.util.function.Consumer; 10 | import java.util.function.Function; 11 | 12 | public class TaskManager { 13 | private static final Logger logger = LoggerFactory.getLogger(TaskManager.class); 14 | private final ExecutorService executorService; 15 | 16 | public TaskManager(int threadCount) { 17 | this.executorService = Executors.newFixedThreadPool(threadCount); 18 | } 19 | 20 | public List processTasks( 21 | List items, 22 | Function taskFactory, 23 | Consumer resultProcessor) { 24 | 25 | List results = new ArrayList<>(); 26 | int totalTasks = items.size(); 27 | int completedTasks = 0; 28 | int lastReportedPercentage = 0; 29 | 30 | try { 31 | // 创建所有任务 32 | List> futures = new ArrayList<>(); 33 | for (T item : items) { 34 | DecompileTask task = taskFactory.apply(item); 35 | futures.add(executorService.submit(task)); 36 | } 37 | 38 | // 处理结果 39 | for (Future future : futures) { 40 | try { 41 | DecompileResult result = future.get(); 42 | results.add(result); 43 | 44 | // 处理结果 45 | if (resultProcessor != null) { 46 | resultProcessor.accept(result); 47 | } 48 | 49 | // 更新和报告进度 50 | completedTasks++; 51 | int percentage = (completedTasks * 100) / totalTasks; 52 | if (percentage >= lastReportedPercentage + 10 || completedTasks == totalTasks) { 53 | logger.info("Progress: {}% ({} of {} files)", 54 | percentage, completedTasks, totalTasks); 55 | lastReportedPercentage = percentage; 56 | } 57 | 58 | } catch (InterruptedException | ExecutionException e) { 59 | logger.error("Task execution failed", e); 60 | } 61 | } 62 | } finally { 63 | executorService.shutdown(); 64 | try { 65 | if (!executorService.awaitTermination(1, TimeUnit.MINUTES)) { 66 | executorService.shutdownNow(); 67 | } 68 | } catch (InterruptedException e) { 69 | executorService.shutdownNow(); 70 | Thread.currentThread().interrupt(); 71 | } 72 | } 73 | 74 | return results; 75 | } 76 | public void executeParallel(List> tasks) { 77 | if (tasks.isEmpty()) { 78 | return; 79 | } 80 | 81 | try { 82 | List> futures = new ArrayList<>(); 83 | for (Callable task : tasks) { 84 | futures.add(executorService.submit(task)); 85 | } 86 | 87 | // 等待所有任务完成 88 | for (Future future : futures) { 89 | try { 90 | future.get(); 91 | } catch (ExecutionException | InterruptedException e) { 92 | logger.error("任务执行失败", e); 93 | } 94 | } 95 | 96 | logger.info("完成了 {} 个并行任务", tasks.size()); 97 | } catch (Exception e) { 98 | logger.error("并行任务执行过程中发生错误", e); 99 | } 100 | } 101 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/util/FileUtil.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.util; 2 | 3 | import com.decompiler.model.DecompileJob; 4 | import com.decompiler.task.TaskManager; 5 | import org.apache.commons.io.FileUtils; 6 | import org.apache.commons.io.FilenameUtils; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import java.io.File; 11 | import java.io.FileNotFoundException; 12 | import java.io.IOException; 13 | import java.nio.file.Files; 14 | import java.nio.file.Path; 15 | import java.util.ArrayList; 16 | import java.util.Collections; 17 | import java.util.List; 18 | import java.util.concurrent.Callable; 19 | 20 | public class FileUtil { 21 | private static final Logger logger = LoggerFactory.getLogger(FileUtil.class); 22 | 23 | /** 24 | * 处理输入目录,解压所有JAR文件并收集所有class文件 25 | */ 26 | public static List processDirectory(File directory, String outputPath, TaskManager taskManager) throws IOException { 27 | if (!directory.exists()) { 28 | throw new FileNotFoundException("目录不存在: " + directory.getAbsolutePath()); 29 | } 30 | 31 | File outputDir = new File(outputPath); 32 | FileUtils.forceMkdir(outputDir); 33 | 34 | logger.info("处理目录: {}", directory.getAbsolutePath()); 35 | final List jobs = Collections.synchronizedList(new ArrayList<>()); 36 | 37 | // 1. 找出所有JAR文件和class文件 38 | List jarFiles = new ArrayList<>(); 39 | List classFiles = new ArrayList<>(); 40 | 41 | Files.walk(directory.toPath()) 42 | .filter(Files::isRegularFile) 43 | .forEach(path -> { 44 | String fileName = path.toString().toLowerCase(); 45 | File file = path.toFile(); 46 | 47 | if (fileName.endsWith(".jar") || fileName.endsWith(".war") || 48 | fileName.endsWith(".ear") || fileName.endsWith(".aar")) { 49 | jarFiles.add(file); 50 | } else if (fileName.endsWith(".class")) { 51 | classFiles.add(file); 52 | } 53 | }); 54 | 55 | logger.info("找到 {} 个JAR文件和 {} 个class文件", jarFiles.size(), classFiles.size()); 56 | 57 | // 2. 使用TaskManager并行解压所有JAR文件 58 | final List extractedDirs = Collections.synchronizedList(new ArrayList<>()); 59 | // 创建JAR提取任务列表 60 | List> extractionTasks = new ArrayList<>(); 61 | for (File jarFile : jarFiles) { 62 | String jarName = jarFile.getName(); 63 | String dirName = FilenameUtils.getBaseName(jarName); 64 | File extractDir = new File(outputDir, dirName); 65 | 66 | extractionTasks.add(() -> { 67 | try { 68 | JarUtils.extractJar(jarFile, extractDir); 69 | extractedDirs.add(extractDir); 70 | return null; 71 | } catch (Exception e) { 72 | logger.error("解压JAR文件失败: {}", jarFile.getName(), e); 73 | return null; 74 | } 75 | }); 76 | } 77 | 78 | // 并行执行所有JAR提取任务 79 | if (!extractionTasks.isEmpty()) { 80 | taskManager.executeParallel(extractionTasks); 81 | } 82 | 83 | // 3. 收集所有class文件 84 | // 处理原始class文件 85 | for (File classFile : classFiles) { 86 | Path relativePath = directory.toPath().relativize(classFile.toPath().getParent()); 87 | File targetDir = new File(outputDir, relativePath.toString()); 88 | FileUtils.forceMkdir(targetDir); 89 | 90 | File targetFile = new File(targetDir, classFile.getName()); 91 | FileUtils.copyFile(classFile, targetFile); 92 | 93 | jobs.add(new DecompileJob(targetFile, targetDir.getAbsolutePath(), null)); 94 | } 95 | // 处理从JAR中解压出来的class文件 96 | for (File extractDir : extractedDirs) { 97 | List jarClassFiles = new ArrayList<>(); 98 | Files.walk(extractDir.toPath()) 99 | .filter(path -> path.toString().toLowerCase().endsWith(".class")) 100 | .forEach(path -> jarClassFiles.add(path.toFile())); 101 | 102 | logger.info("从 {} 中提取了 {} 个class文件", extractDir.getName(), jarClassFiles.size()); 103 | 104 | for (File classFile : jarClassFiles) { 105 | String outputDirPath = classFile.getParent(); 106 | jobs.add(new DecompileJob(classFile, outputDirPath, null)); 107 | } 108 | } 109 | 110 | logger.info("总共找到 {} 个待反编译的class文件", jobs.size()); 111 | return jobs; 112 | } 113 | 114 | /** 115 | * 处理单个JAR文件 116 | */ 117 | public static List processJarFile(File jarFile, String outputPath) throws IOException { 118 | if (!jarFile.exists()) { 119 | throw new FileNotFoundException("文件不存在: " + jarFile.getAbsolutePath()); 120 | } 121 | 122 | File outputDir = new File(outputPath); 123 | FileUtils.forceMkdir(outputDir); 124 | 125 | // 解压JAR文件到输出目录 126 | String jarName = jarFile.getName(); 127 | String dirName = FilenameUtils.getBaseName(jarName); 128 | File extractDir = new File(outputDir, dirName); 129 | 130 | JarUtils.extractJar(jarFile, extractDir); 131 | 132 | // 收集所有class文件 133 | List jobs = new ArrayList<>(); 134 | List classFiles = new ArrayList<>(); 135 | 136 | Files.walk(extractDir.toPath()) 137 | .filter(path -> path.toString().toLowerCase().endsWith(".class")) 138 | .forEach(path -> classFiles.add(path.toFile())); 139 | 140 | logger.info("从JAR文件中提取了 {} 个class文件", classFiles.size()); 141 | 142 | for (File classFile : classFiles) { 143 | String outputDirPath = classFile.getParent(); 144 | jobs.add(new DecompileJob(classFile, outputDirPath, null)); 145 | } 146 | 147 | return jobs; 148 | } 149 | 150 | /** 151 | * 处理单个class文件 152 | */ 153 | public static List processClassFile(File classFile, String outputPath) throws IOException { 154 | if (!classFile.exists()) { 155 | throw new FileNotFoundException("文件不存在: " + classFile.getAbsolutePath()); 156 | } 157 | 158 | File outputDir = new File(outputPath); 159 | FileUtils.forceMkdir(outputDir); 160 | 161 | // 复制class文件到输出目录 162 | File targetFile = new File(outputDir, classFile.getName()); 163 | FileUtils.copyFile(classFile, targetFile); 164 | 165 | // 创建反编译任务 166 | List jobs = new ArrayList<>(); 167 | jobs.add(new DecompileJob(targetFile, outputDir.getAbsolutePath(), null)); 168 | 169 | return jobs; 170 | } 171 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/util/JarUtils.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.util; 2 | 3 | import org.apache.commons.io.FileUtils; 4 | import org.apache.commons.io.FilenameUtils; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | import java.io.File; 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | import java.util.Enumeration; 12 | import java.util.jar.JarEntry; 13 | import java.util.jar.JarFile; 14 | 15 | public class JarUtils { 16 | private static final Logger logger = LoggerFactory.getLogger(JarUtils.class); 17 | 18 | /** 19 | * 解压JAR文件到指定目录 20 | */ 21 | public static void extractJar(File jarFile, File outputDir) throws IOException { 22 | if (jarFile == null || !jarFile.exists() || jarFile.length() == 0) { 23 | logger.warn("JAR文件无效或为空: {}", jarFile != null ? jarFile.getName() : "null"); 24 | return; 25 | } 26 | 27 | logger.info("解压JAR文件: {} 到 {}", jarFile.getName(), outputDir.getAbsolutePath()); 28 | 29 | // 确保输出目录存在 30 | FileUtils.forceMkdir(outputDir); 31 | 32 | try (JarFile jar = new JarFile(jarFile)) { 33 | Enumeration entries = jar.entries(); 34 | int extractedFiles = 0; 35 | 36 | while (entries.hasMoreElements()) { 37 | JarEntry entry = entries.nextElement(); 38 | String entryName = entry.getName(); 39 | File outFile = new File(outputDir, entryName); 40 | 41 | if (entry.isDirectory()) { 42 | FileUtils.forceMkdir(outFile); 43 | } else { 44 | // 确保父目录存在 45 | FileUtils.forceMkdirParent(outFile); 46 | 47 | try (InputStream in = jar.getInputStream(entry)) { 48 | FileUtils.copyInputStreamToFile(in, outFile); 49 | extractedFiles++; 50 | } catch (IOException e) { 51 | logger.warn("解压文件失败: {} - {}", entryName, e.getMessage()); 52 | } 53 | } 54 | } 55 | 56 | logger.info("从JAR文件 {} 解压了 {} 个文件", jarFile.getName(), extractedFiles); 57 | } catch (Exception e) { 58 | logger.error("解压JAR文件失败: {}", jarFile.getName(), e); 59 | throw new IOException("解压JAR文件失败: " + e.getMessage(), e); 60 | } 61 | } 62 | 63 | /** 64 | * 检查文件是否是JAR文件 65 | */ 66 | public static boolean isJarFile(File file) { 67 | if (file == null || !file.exists() || file.isDirectory() || file.length() == 0) { 68 | return false; 69 | } 70 | 71 | String name = file.getName().toLowerCase(); 72 | return name.endsWith(".jar") || name.endsWith(".war") || 73 | name.endsWith(".ear") || name.endsWith(".aar"); 74 | } 75 | } -------------------------------------------------------------------------------- /src/main/java/com/decompiler/util/VineDecompiler.java: -------------------------------------------------------------------------------- 1 | package com.decompiler.util; 2 | 3 | import org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler; 4 | import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; 5 | 6 | import java.io.File; 7 | import java.util.Map; 8 | 9 | /** 10 | * Vineflower 反编译器包装类 11 | * 通过继承 ConsoleDecompiler 来访问其 protected 构造函数 12 | */ 13 | public class VineDecompiler extends ConsoleDecompiler { 14 | 15 | /** 16 | * 创建一个VineDecompiler实例 17 | * 18 | * @param destination 输出目录 19 | * @param options 反编译选项 20 | * @param logger 日志记录器 21 | */ 22 | public VineDecompiler(File destination, Map options, IFernflowerLogger logger) { 23 | super(destination, options, logger); 24 | } 25 | 26 | /** 27 | * 创建一个VineDecompiler实例 28 | * 29 | * @param destination 输出目录 30 | * @param options 反编译选项 31 | * @param logger 日志记录器 32 | * @param saveType 保存类型 33 | */ 34 | public VineDecompiler(File destination, Map options, IFernflowerLogger logger, SaveType saveType) { 35 | super(destination, options, logger, saveType); 36 | } 37 | } -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ${CONSOLE_LOG_PATTERN} 10 | UTF-8 11 | 12 | 13 | 14 | 15 | 16 | logs/decompiler.log 17 | 18 | logs/decompiler-%d{yyyy-MM-dd}.%i.log 19 | 10MB 20 | 30 21 | 1GB 22 | 23 | 24 | %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %msg%n 25 | UTF-8 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/test/java/Test.java: -------------------------------------------------------------------------------- 1 | import com.decompiler.Decompiler; 2 | import com.decompiler.config.DecompilerConfig; 3 | import com.decompiler.config.OptionsBuilder; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import java.io.IOException; 8 | import java.util.Map; 9 | 10 | public class Test { 11 | private static final Logger logger = LoggerFactory.getLogger(Test.class); 12 | 13 | public static void main(String[] args) throws IOException { 14 | DecompilerConfig config = new DecompilerConfig.Builder() 15 | .inputPath("/xxxx/code") 16 | .outputPath("/xxxx/output") 17 | .threadCount(8) 18 | .deleteClassFiles(true) 19 | .build(); 20 | OptionsBuilder optionsBuilder = new OptionsBuilder(); 21 | Map vineflowerOptions = optionsBuilder.build(); 22 | Decompiler decompiler = new Decompiler(config, vineflowerOptions); 23 | long startTime = System.currentTimeMillis(); 24 | decompiler.execute(); 25 | 26 | long endTime = System.currentTimeMillis(); 27 | double totalTime = (endTime - startTime) / 1000.0; 28 | logger.info("总耗时: " + totalTime + " 秒"); 29 | } 30 | } 31 | --------------------------------------------------------------------------------