How to compile rhino/javascript files to .class bytecode for java at runtime

核能气质少年 提交于 2019-12-03 03:31:02

There's a short tutorial here:

You can compile your scripts at runtime using Context.compileString(). This produces a Script object which you can reuse.

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

The performance difference between something like this and using Context.evaluateString() could easily be multiple orders of magnitude faster.

You can try the follow sample:

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 );
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!