eclipsesource / J2V8

Java Bindings for V8
2.55k stars 355 forks source link

About new a java object #503

Open liu1352183717 opened 4 years ago

liu1352183717 commented 4 years ago

Hello there! I would like to ask if it is possible to achieve a new java object in the v8 environment Or provide a function that returns a java object

ahmadov commented 4 years ago

Hi,

Are you looking for that? The following code registers MyClass Java class in JavaScript environment, also registers its methods.

import com.eclipsesource.v8.V8;
import com.eclipsesource.v8.V8Object;

public class Main {
    public static void main(String[] args) {

        V8 runtime = V8.createV8Runtime();
        new MyClass().initialize(runtime);

        runtime.executeVoidScript("var myObj = new MyClass();"
                + "myObj.helloWorld();"
                + "myObj.print('foo');");
    }
}

class MyClass {

    public void initialize(V8 runtime) {
        runtime.registerJavaMethod(this, "myClassJsConstructor", "MyClass", new Class<?>[] { V8Object.class }, true);

        V8Object obj = runtime.getObject("MyClass");
        V8Object prototype = runtime.executeObjectScript("MyClass.prototype");

        prototype.registerJavaMethod(this, "helloWorld", "helloWorld", null);
        prototype.registerJavaMethod(this, "print", "print", new Class<?>[] { String.class });

        obj.setPrototype(prototype);
    }

    public void helloWorld() {
        System.out.println("Hello world!");
    }

    public void print(String message) {
        System.out.println(message);
    }

    public void myClassJsConstructor(V8Object obj) {}
}
liu1352183717 commented 4 years ago

Yes, it's a bit similar! Can this method directly access the system's java classes?

liu1352183717 commented 4 years ago

I want to perform operations like java, can import java classes

ahmadov commented 4 years ago

Yes, registered methods can access all Java classes, as you see in the example, both methods access System Java class.

liu1352183717 commented 4 years ago

Oh, thanks for your answer. If I want to return a java object, do I need to convert it to a js object?

ahmadov commented 4 years ago

you can't return a Java object directly, you have to convert either to V8Object or V8Value.

liu1352183717 commented 4 years ago

But I don't know how to convert, can you give an example? I'm so stupid!