How to embed V8 in a Java application?

后端 未结 3 362
遇见更好的自我
遇见更好的自我 2021-01-30 22:14

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

Have you got some solutions?

3条回答
  •  旧时难觅i
    2021-01-30 23:13

    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.

    
        
            com.eclipsesource.j2v8
            j2v8_macosx_x86_64
            2.0
            compile
        
    
    

提交回复
热议问题