【问题标题】:How to compile rhino/javascript files to .class bytecode for java at runtime如何在运行时将 rhino/javascript 文件编译为 java 的 .class 字节码
【发布时间】:2011-04-20 03:06:27
【问题描述】:

我正在用 Java 制作 falling sand game。我希望用户能够使用更简单的语言为其编写自己的引擎。落沙游戏可能会占用大量 CPU,因此我希望引擎尽可能快地运行,而不必手动编译。

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

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

【问题讨论】:

  • 那你基本知道怎么做了吧?但是您希望这是动态完成的,并且用户不必费心将 rhino 脚本更改为 .class?为此,您可以为他们提供一个批处理文件来满足您的目的......

标签: java javascript runtime compilation rhino


【解决方案1】:

这里有一个简短的教程:

【讨论】:

  • 本文的代码示例有一个小瑕疵,就是函数fib(num);的调用应该在it的定义后面。谢谢。
  • 这篇文章明确指出,rhino 不能将 .js 编译为 .class,虽然可以。
【解决方案2】:
【解决方案3】:

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

Script s = someContext.compileString(myScript, "<cmd>", 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() 之间的性能差异很容易快多个数量级。

【讨论】:

    【解决方案4】:

    您可以尝试以下示例:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多