《Java核心技术 卷II》编译器API

编译器API

调用编译器

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

发起编译任务

JavaCompiler.CompilationTask task = compiler.getTask(......);

package 第8章脚本编译与注解;

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }

}
package 第8章脚本编译与注解;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class JavaCompilerAdvancedExample {
    public static void main(String[] args) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            System.out.println("Could not get Java compiler.");
            return;
        }

        String sourceFilePath = "./src/第8章脚本编译与注解/HelloWorld.java";
        File sourceFile = new File(sourceFilePath);

        // 自定义输出目录
        String outputDirectory = "./src/第8章脚本编译与注解/output";
        File outputDir = new File(outputDirectory);
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }

        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> compilationUnits;
        try {
            compilationUnits = fileManager.getJavaFileObjects(sourceFile);
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null,
                    Arrays.asList("-d", outputDirectory), null, compilationUnits);
            boolean success = task.call();
            if (success) {
                System.out.println("Compilation successful.");
            } else {
                System.out.println("Compilation failed.");
            }
        } finally {
            try {
                if (fileManager!= null) {
                    fileManager.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿立聊全栈

有作用的,有闲钱的支持一点。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值