Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 700
aexyl93 Avatar asked Oct 02 '10 01:10

aexyl93


3 Answers

There's a short tutorial here:

  • Scripting: Compiling Scripts in Java
like image 189
ars Avatar answered Nov 03 '22 11:11

ars


My solution here: Has anyone used or written an Ant task to compile (Rhino) JavaScript to Java bytecode?

like image 45
jbeard4 Avatar answered Nov 03 '22 11:11

jbeard4


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.

like image 1
Jeb Avatar answered Nov 03 '22 13:11

Jeb