Open liu1352183717 opened 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) {}
}
Yes, it's a bit similar! Can this method directly access the system's java classes?
I want to perform operations like java, can import java classes
Yes, registered methods can access all Java classes, as you see in the example, both methods access System
Java class.
Oh, thanks for your answer. If I want to return a java object, do I need to convert it to a js object?
you can't return a Java object directly, you have to convert either to V8Object or V8Value.
But I don't know how to convert, can you give an example? I'm so stupid!
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