如何在运行时将rhino / javascript文件编译为.class字节码

我正在用Java制作一个落砂游戏 。 我希望用户能够使用更简单的语言为其编写自己的引擎。 落砂游戏可能会占用大量CPU资源,因此我希望尽可能快地运行引擎,而无需手动编译。

我需要知道如何在运行时将rhino javascript文件编译为.class文件以供使用。

我找了一种方法,但除了使用我不希望用户必须执行的命令行手动编译之外,找不到任何方法。

这里有一个简短的教程:

  • 脚本:用Java编译脚本

我的解决方案: 有没有人使用或编写过Ant任务来编译(Rhino)JavaScript到Java字节码?

您可以使用Context.compileString()在运行时编译脚本。 这会生成一个可以重用的Script对象。

 Script s = someContext.compileString(myScript, "", 1, null); // Store s, cache it in a map or something, maybe even serialize and persist it. // Later... Object result = s.exec(anotherContext, someScope); 

像这样和使用Context.evaluateString()之类的性能差异可以轻松地快几个数量级。

您可以尝试以下示例:

 void toClassFile( String script ) throws IOException { CompilerEnvirons compilerEnv = new CompilerEnvirons(); ClassCompiler compiler = new ClassCompiler( compilerEnv ); Object[] compiled = compiler.compileToClassFiles( script, null, 1, "javascript.Test" ); for( int j = 0; j != compiled.length; j += 2 ) { String className = (String)compiled[j]; byte[] bytes = (byte[])compiled[(j + 1)]; File file = new File( className.replace( '.', '/' ) + ".class" ); file.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream( file )) { fos.write( bytes ); } } }