Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed V8 in a Java application?

I'm looking for a solution for embedding the Google JavaScript engine V8 in my Java application.

Have you got some solutions?

like image 388
Stephan Avatar asked Jun 16 '11 09:06

Stephan


People also ask

How do you run a V8 engine?

On Mac OS X be sure to have brew installed. Then just run the command (sudo) brew install v8 , depending on your machine this may take some time. To start the V8 console, just run v8 - Voilà! Tip: To quit the console, just run quit() and don't forget the parentheses!

What is V8 instance?

In V8, a context is an execution environment that allows separate, unrelated, JavaScript applications to run in a single instance of V8. You must explicitly specify the context in which you want any JavaScript code to be run.

What is Chrome's V8 JavaScript engine?

Chrome V8 is a JavaScript engine, which means that it executes JavaScript code. Originally, JavaScript was written to be executed by web browsers. Chrome V8, or just V8, can execute JavaScript code either within or outside of a browser, which makes server-side scripting possible.


2 Answers

You can use J2V8 https://github.com/eclipsesource/J2V8. It's even available in Maven Central.

Below is a Hello, World! program using J2V8.

package com.example;  import com.eclipsesource.v8.V8;  public class EclipseCon_snippet5 {       public static class Printer {         public void print(String string) {             System.out.println(string);         }     }      public static void main(String[] args) {         V8 v8 = V8.createV8Runtime();         v8.registerJavaMethod(new Printer(), "print", "print", new Class<?>[]{String.class});         v8.executeVoidScript( "print('Hello, World!');" );         v8.release(true);     }  } 

You will need to specify your platform in your pom.xml. J2V8 currently supports win32_x86, macosx_x86_64, android_x86 and android_armv7l. The reason they are different is because of the native bindings and pre-build version of V8 that is bundled.

For example, on MacOS you can use.

<dependencies>     <dependency>         <groupId>com.eclipsesource.j2v8</groupId>         <artifactId>j2v8_macosx_x86_64</artifactId>         <version>2.0</version>         <scope>compile</scope>     </dependency> </dependencies> 
like image 115
irbull Avatar answered Sep 28 '22 06:09

irbull


Maybe you could try Jav8, which implement the Java Scripting API (JSR223) base on the Google V8 Javascript engine. I'm working on it from weeks ago, and it could support most simple scenes.

http://code.google.com/p/jav8/

like image 28
Flier Lu Avatar answered Sep 28 '22 06:09

Flier Lu