How to embed V8 in a Java application?

吃可爱长大的小学妹 提交于 2019-12-03 03:56:48

问题


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

Have you got some solutions?


回答1:


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>



回答2:


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/




回答3:


There's not really any straightforward way you can do it, but, I would suggest Rhino or the JNI. The former is easier, but, not v8, the latter is hard and finicky, but, v8.

Or, you can use a seperate v8 process, and talk with it with Java.



来源:https://stackoverflow.com/questions/6369919/how-to-embed-v8-in-a-java-application

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