java编译 类的加载_java如何动态编译和加载外部Java类?

小编典典

以下内容基于JavaDocs中给出的示例

这会将a保存File在testcompile目录中(基于package名称要求),然后将其编译File为Java类。

package inlinecompiler;

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;

import javax.tools.Diagnostic;

import javax.tools.DiagnosticCollector;

import javax.tools.JavaCompiler;

import javax.tools.JavaFileObject;

import javax.tools.StandardJavaFileManager;

import javax.tools.ToolProvider;

public class InlineCompiler {

public static void main(String[] args) {

StringBuilder sb = new StringBuilder(64);

sb.append("package testcompile;\n");

sb.append("public class HelloWorld implements inlinecompiler.InlineCompiler.DoStuff {\n");

sb.append(" public void doStuff() {\n");

sb.append(" System.out.println(\"Hello world\");\n");

sb.append(" }\n");

sb.append("}\n");

File helloWorldJava = new File("testcompile/HelloWorld.java");

if (helloWorldJava.getParentFile().exists() || helloWorldJava.getParentFile().mkdirs()) {

try {

Writer writer = null;

try {

writer = new FileWriter(helloWorldJava);

writer.write(sb.toString());

writer.flush();

} finally {

try {

writer.close();

} catch (Exception e) {

}

}

/** Compilation Requirements *********************************************************************************************/

DiagnosticCollector diagnostics = new DiagnosticCollector();

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

// This sets up the class path that the compiler will use.

// I've added the .jar file that contains the DoStuff interface within in it...

List 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);

/********************************************************************************************* Compilation Requirements **/

if (task.call()) {

/** Load and execute *************************************************************************************************/

System.out.println("Yipe");

// Create a new custom class loader, pointing to the directory that contains the compiled

// classes, this should point to the top of the package structure!

URLClassLoader classLoader = new URLClassLoader(new URL[]{new File("./").toURI().toURL()});

// Load the class from the classloader by name....

Class> loadedClass = classLoader.loadClass("testcompile.HelloWorld");

// Create a new instance...

Object obj = loadedClass.newInstance();

// Santity check

if (obj instanceof DoStuff) {

// Cast to the DoStuff interface

DoStuff stuffToDo = (DoStuff)obj;

// Run it baby

stuffToDo.doStuff();

}

/************************************************************************************************* Load and execute **/

} else {

for (Diagnostic extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {

System.out.format("Error on line %d in %s%n",

diagnostic.getLineNumber(),

diagnostic.getSource().toUri());

}

}

fileManager.close();

} catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException exp) {

exp.printStackTrace();

}

}

}

public static interface DoStuff {

public void doStuff();

}

}

现在已更新,包括为编译器提供类路径以及已编译类的加载和执行!

2020-02-29

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值