如何在不使用JDK的情况下从tools.jar使用JavaCompiler [英] How to use JavaCompiler from tools.jar without JDK

查看:68
本文介绍了如何在不使用JDK的情况下从tools.jar使用JavaCompiler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个可以在运行时编译提供的 .java 文件的应用程序.我知道JDK的 tools.jar 中有一个可用的程序化编译器.但是,我不能保证该应用程序的用户具有JDK.我试图将 tools.jar 打包到应用程序中,并将其作为库引用.当我将 tools.jar 添加到类路径的Bootstrap条目中时,这似乎在Eclipse IDE中起作用.将应用程序导出到可运行的jar(与 tools.jar 一起打包)时, ToolProvider.getSystemJavaCompiler(); 返回 null .我不确定问题到底是什么,但是我认为这可能与将应用程序导出到可运行jar时无法正确保留类路径的Bootstrap条目有关.有任何想法吗?我可以使用 tools.jar 编译器的替代方法吗?多谢您的耐心配合,因为这是我在这里发布的第一个问题!

I am trying to create an application that can compile a provided .java file during runtime. I understand that there is a programmatical compiler available within the tools.jar of the JDK. However, I cannot guarantee that the user of the application has JDK. I have attempted to package tools.jar within the application and reference it as a library. This seems to work within the Eclipse IDE when I have tools.jar added into the Bootstrap Entries of the classpath. When exporting the application to a runnable jar (with tools.jar packaged with it), ToolProvider.getSystemJavaCompiler(); returns null. I am not exactly sure what the issue is, but I believe it may have to do with the Bootstrap Entries of the classpath not being properly preserved when the application is exported to a runnable jar. Any ideas? Are there any alternatives to the tools.jar compiler that I could use? Thanks for your patience, as this is my first question posted here!

推荐答案

您需要在"tools.jar"中使用编译器

You need to use the compiler within "tools.jar"

ToolProvider.getSystemJavaCompiler()

将根据path变量中定义的jdk返回编译器,您可以改为:

will return the compiler from the jdk defined in the path variable, you can do this instead:

File file = new File(pathToToolsJar);
URL[] urls = new URL[]{ file.toURI().toURL() };
ClassLoader loader = new URLClassLoader(urls);
Class compilerClass = loader.loadClass("com.sun.tools.javac.api.JavacTool");
JavaCompiler compiler = (JavaCompiler) compilerClass.getConstructor().newInstance();

或者您可以在编译时将tools.jar添加为库

Or you can add tools.jar as a library at compile time

import com.sun.tools.javac.api.JavacTool;
...
JavaCompiler compiler = new JavacTool();

或者您可以更改系统属性,但这会导致意外行为

Or you can change System properties, but that leads to unexpected behaviors

这篇关于如何在不使用JDK的情况下从tools.jar使用JavaCompiler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆