You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ByteBuddy保存Java源代码?

ByteBuddy生成类时同时保存Java源码的方案

ByteBuddy本身没有提供直接生成并保存Java源码(.java)的API,saveIn(File)确实只能写入字节码文件。不过可以通过**「生成字节码后反编译为源码」**的方式实现需求,具体步骤如下:

实现思路

  1. 用ByteBuddy正常生成并保存.class文件
  2. 借助第三方反编译库(比如Procyon、JD-Core)读取.class文件,将其反编译为Java源码字符串
  3. 将源码字符串写入对应的.java文件

具体实现(以Procyon为例)

1. 添加反编译库依赖

如果用Maven,在pom.xml中添加Procyon的依赖:

<dependency>
    <groupId>org.bitbucket.mstrobel</groupId>
    <artifactId>procyon-compilertools</artifactId>
    <version>0.6.0</version>
    <scope>runtime</scope>
</dependency>

2. 完整代码示例

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import org.bitbucket.mstrobel.decompiler.Decompiler;
import org.bitbucket.mstrobel.decompiler.DecompilerSettings;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class ByteBuddySourceSaver {
    public static void main(String[] args) throws IOException {
        // 1. 用ByteBuddy动态生成类
        DynamicType.Unloaded<?> dynamicClass = new ByteBuddy()
                .subclass(Object.class)
                .name("com.example.MyGeneratedClass")
                .defineMethod("greet", String.class, Visibility.PUBLIC)
                .intercept(net.bytebuddy.implementation.FixedValue.value("Hello from generated class!"))
                .make();

        // 2. 保存.class文件到指定目录
        File classOutputDir = new File("target/classes");
        dynamicClass.saveIn(classOutputDir);

        // 3. 定位生成的.class文件
        File classFile = new File(classOutputDir, "com/example/MyGeneratedClass.class");

        // 4. 用Procyon反编译字节码为Java源码
        DecompilerSettings settings = DecompilerSettings.javaDefaults();
        String sourceCode = Decompiler.decompile(classFile.getAbsolutePath(), settings);

        // 5. 保存.java文件到源码目录
        File sourceOutputDir = new File("target/generated-sources/java");
        sourceOutputDir.mkdirs();
        File javaFile = new File(sourceOutputDir, "com/example/MyGeneratedClass.java");
        javaFile.getParentFile().mkdirs(); // 创建包路径目录

        try (FileWriter writer = new FileWriter(javaFile)) {
            writer.write(sourceCode);
        }
    }
}

补充说明

  • 除了Procyon,也可以用JD-Core(JD-GUI的核心库)实现反编译,用法逻辑类似
  • 反编译生成的源码可能和手写代码有格式差异,但功能完全一致,可读性也能满足需求
  • 如果需要高度定制的源码格式,也可以尝试在构建ByteBuddy类时手动拼接源码字符串,但这种方式维护成本高,不如反编译方案高效可靠

内容的提问来源于stack exchange,提问作者MaduKan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 19:16:12