您不必编写大量代码以使 Java 以源代码形式执行,您有以下几种选择:
使用 Scala!你知道 Scala 是基于 Java 构建的吗?它有一个解释器和编译器。您可以运行脚本、shell 或编译并运行它。 Scala 和 Java 无缝协作。两者都编译为相同的字节码并在 JVM 上运行。是的,这种语言会让人感觉很奇怪,因为 Scala 就像是 Java、R 和 Python 之间的交叉,但大多数核心语言都没有改变,所有 Java 包都可用。试试 Scala。如果你在 Linux 上,你不妨也看看 Spark,即使是一台机器。
如果你坚持只使用 Java,你可以创建一个混合程序来做两件事(我以前做过):编译代码并运行它。可执行文件甚至 bash 脚本可以完成获取源文件并使它们可执行的工作。如果您正在寻找制作 Java shell,那么您需要制作一个动态运行时编译器/加载器,但您只需要使用 Java/Oracle 已经提供给我们的东西。想象一下从我放置打印语句的文件中插入 Java 语法。只要它可以编译,你就可以在那里拥有任何你想要的东西。看这个例子:
package util.injection;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
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 Compiler {
static final long t0 = System.currentTimeMillis();
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(64);
String packageName = "util";
String className = "HelloWorld";
sb.append("package util;\n");
sb.append("public class HelloWorld extends " + Function.class.getName() + " {\n");
sb.append(" public void test() {\n");
sb.append(" System.out.println(\"Hello from dynamic function!\");\n");
sb.append(" }\n");
sb.append("}\n");
String code = sb.toString();
String jarLibraryFile = "target/myprojectname.jar";
Function dynFunction = code2class(packageName, className, code, jarLibraryFile);
dynFunction.test();
}
public static Function code2class(String packageName, String className, String code, String jarLibraryFile) {
String wholeClassName = packageName.replace("/", ".") + "." + className;
String fileName = wholeClassName.replace(".", "/") + ".java";//"testcompile/HelloWorld.java";
File javaCodeFile = new File(fileName);
string2file(javaCodeFile, code);
Function dynFunction = null;
try {
boolean success = compile(jarLibraryFile, javaCodeFile);
/**
* Load and execute
* ************************************************************************************************
*/
System.out.println("Running... " + (System.currentTimeMillis() - t0) + " ms");
Object obj = load(wholeClassName);
// Santity check
if (obj instanceof Function) {
dynFunction = (Function) obj;
// Run it
//Edit: call dynFunction.test(); to see something
}
System.out.println("Finished... " + (System.currentTimeMillis() - t0) + " ms");
} catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException exp) {
exp.printStackTrace();
}
return dynFunction;
}
public static boolean compile(String jarLibraryFile, File javaCodeFile) throws IOException {
/**
* Compilation Requirements
* ********************************************************************************************
*/
System.out.println("Compiling... " + (System.currentTimeMillis() - t0) + " ms");
DiagnosticCollector<JavaFileObject> 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<String> optionList = new ArrayList<>(2);
optionList.add("-classpath");
optionList.add(System.getProperty("java.class.path") + ";" + jarLibraryFile);
Iterable<? extends JavaFileObject> compilationUnit
= fileManager.getJavaFileObjectsFromFiles(Arrays.asList(javaCodeFile));
JavaCompiler.CompilationTask task = compiler.getTask(
null,
fileManager,
diagnostics,
optionList,
null,
compilationUnit);
fileManager.close();
/**
* *******************************************************************************************
* Compilation Requirements *
*/
if (task.call()) {
return true;
/**
* ***********************************************************************************************
* 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());
System.out.printf("Code = %s\nMessage = %s\n", diagnostic.getCode(), diagnostic.getMessage(Locale.US));
}
}
return false;
}
public static void string2file(File outputFile, String code) {
if (outputFile.getParentFile().exists() || outputFile.getParentFile().mkdirs()) {
try {
Writer writer = null;
try {
writer = new FileWriter(outputFile);
writer.write(code);
writer.flush();
} finally {
try {
writer.close();
} catch (Exception e) {
}
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
public static Object load(String wholeClassName) throws IllegalAccessException, InstantiationException, ClassNotFoundException, MalformedURLException {
// 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(wholeClassName);
// Create a new instance...
Object obj = loadedClass.newInstance();
return obj;
}
}
..
package util.injection;
public class Function {
private static final long serialVersionUID = 7526472295622776147L;
public void test() {
System.out.println("Hello from original Function!");
}
public int getID() {
return -1;
}
public void apply(float[] img, int x, int y) {
}
public double dot(double[] x, double[] y) {
return 0;
}
}