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

4

6

I'm making a falling sand game in Java. I want users to be able to write their own engine for it using a simpler language. Falling sand games can be very CPU intensive so I want to have the engine running as fast as possible while not having to manually compile.

I need to know how to compile rhino javascript files to .class files by at runtime to be used.

I've looked for a way but couldn't find any other than manually compiling it by using the command line which I don't want users to have to do.

Ninon answered 2/10, 2010 at 1:35 Comment(1)
So you basically know how to do it? but you want this to be done dynamically and user need not bother about changing rhino script to .class? for this you can provide them with a batch file that can server your purpose...Frazzle
A
4

There's a short tutorial here:

Ascensive answered 2/10, 2010 at 1:43 Comment(2)
The code sample in this article have a little flaw, That is the calling of function fib(num); should be behind of the definition of the it . thanks.Cargo
This article clearly states, that rhino can't compile .js to .class, although it could.Hazel
H
1

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.

Hydrocarbon answered 19/1, 2012 at 18:11 Comment(0)
J
0

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 );
        }
    }
}
Jocularity answered 19/4, 2015 at 16:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.