如何动态编译和加载外部 Java 类
在创建允许用户通过插件自定义功能的程序时,必须拥有编译和加载外部 Java 类的能力。以下是有关如何实现此目标的综合指南:
使用 JavaCompiler
对于动态编译,请使用 JavaCompiler 类。以下是基于 JavaDocs 的示例:
import javax.tools.*; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class DynamicCompilation { public static void main(String[] args) { // Write the class to a file File helloWorldJava = new File("testcompile/HelloWorld.java"); ... // Compile the file DiagnosticCollector<javafileobject> diagnostics = new DiagnosticCollector(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); // Set the classpath List<string> optionList = new ArrayList(); optionList.add("-classpath"); optionList.add(System.getProperty("java.class.path") + File.pathSeparator + "dist/InlineCompiler.jar"); Iterable extends JavaFileObject> compilationUnit = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava)); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnit); if (task.call()) { // Load and execute the compiled class URLClassLoader classLoader = new URLClassLoader(new URL[]{new File("./").toURI().toURL()}); Class> loadedClass = classLoader.loadClass("testcompile.HelloWorld"); Object obj = loadedClass.newInstance(); if (obj instanceof DoStuff) { DoStuff stuffToDo = (DoStuff) obj; stuffToDo.doStuff(); } } else { ... } fileManager.close(); } public static interface DoStuff { public void doStuff(); } }</string></javafileobject>
此代码演示了如何创建 Java 文件,使用 JavaCompiler 编译它,以及使用自定义 ClassLoader 加载和执行编译后的类。请注意,此示例包含编译器的 ClassPath。
其他资源
- [JavaCompiler API](https://docs.oracle.com/javase /7/docs/api/javax/tools/JavaCompiler.html)
- [类加载器API](https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html)
以上是如何使用JavaCompiler动态编译和加载外部Java类?的详细内容。更多信息请关注PHP中文网其他相关文章!

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生产性。1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允许CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java实现“一次编写,到处运行”通过编译成字节码并在Java虚拟机(JVM)上运行。1)编写Java代码并编译成字节码。2)字节码在任何安装了JVM的平台上运行。3)使用Java原生接口(JNI)处理平台特定功能。尽管存在挑战,如JVM一致性和平台特定库的使用,但WORA大大提高了开发效率和部署灵活性。

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3汉化版
中文版,非常好用

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3 Linux新版
SublimeText3 Linux最新版

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。