How to extend a Java interface or class with overloaded methods using Nashorn?

Christopher Brown christopherbrown06 at gmail.com
Mon Feb 16 07:53:09 UTC 2015


Hello,

Maybe this is answered somewhere ; I tried looking here (maybe missed it
though):
https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions

How should you provide a JavaScript implemention using Nashorn of a Java
interface such as this:

 package baz;

 public interface Foo {
  void bar();
  void bar(String s);
  void bar(Integer i);
  void bar(Object ... varargs);
 }

Assuming that it's straightforward to load "Foo" using Java.type (or other
approaches suggested in answer to my previous e-mail), how would I actually
go about defining the implementation?

 var Foo = Java.type('baz.Foo');
 var instance = new Foo {
  bar: new function(){
   // how do I know which arguments were passed?
   // how do I define the other signatures?
  }
 };

I'm guessing that I can only define one "bar" function, is that right?
Should I try and detect which variant was invoked by using the implicit
"arguments" array, or should I define some formal parameters (and how would
that map to values which defined as scalars in some cases, and collections
in others)?

If there's a Nashorn-specific way of defining specific signatures (there IS
an example, "explicit method selection", with as cast to
out["println(int)"], but that's not the direction I'm looking for), how can
a JavaScript calling method select the intended overload?

Thanks,
Christopher


More information about the nashorn-dev mailing list