graaljs icon indicating copy to clipboard operation
graaljs copied to clipboard

Could use docs on how to implement a Java interface or class from JavaScript

Open mikehearn opened this issue 6 years ago • 4 comments

You can do this in Nashorn but the equivalent approaches in GraalJS don't seem to work (yet?). The JavaInterop.md file doesn't say how to do it either. This makes it hard to implement callbacks from Java->JavaScript that use complex interfaces.

mikehearn avatar Aug 27 '18 21:08 mikehearn

You can do this with Java.extend (which works similarly to Nashorn), e.g.:

var R = Java.extend(Java.type("java.lang.Runnable"));
var r = new R(function(){print("hello");});
r.run();

or:

var C = Java.extend(Java.type("some.AbstractClass"));
var c = new C({
  someMethod: function() {/*...*/},
  otherMethod: function() {/*...*/},
  toString() {return "MyClass";}
});
c.someMethod();

woess avatar Aug 28 '18 17:08 woess

Thanks! Could Java interop be extended to do this automatically when the parameter type of the invoked method could be satisfied this way?

mikehearn avatar Aug 29 '18 15:08 mikehearn

@mikehearn for interfaces that should already be the case, but unfortunately not for classes. We'll consider extending Java interop to do this in the future.

woess avatar Aug 29 '18 16:08 woess

You're right - I tried it with a simpler case and it worked. It's only the case where there are multiple overloads that doesn't seem to work yet.

mikehearn avatar Aug 29 '18 19:08 mikehearn