Using a script to implement a Java interface with variadic methods
John Keeping
john at metanate.com
Wed Mar 27 07:54:53 PDT 2013
I get surprising results using Nashorn to implement a Java interface via
a script when that interface contains variadic methods.
The easiest way to explain is probably with an example:
If I have a Java interface:
public interface MyInterface {
void test(int i, String... strings);
}
and I implement this in a script:
function test(i, strings) {
print('i = ' + i);
print('strings = ' + strings);
}
which I then wrap from Java:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(script);
Invocable inv = (Invocable) engine;
MyInterface obj = inv.getInterface(MyInterface.class);
Calling the "test" method:
obj.test(10, "one", "two", "three");
gives:
i = 10
strings = one
when I would expect something like:
i = 10
strings = [Ljava.lang.String;@deadbeef
(not useful output, but it illustrates the point I hope).
At this point, I considered changing the script to use "arguments" to
access the passed in values:
function test(i, strings) {
for (var index = 0; index < arguments.length; index++)
print('arg ' + index + ' = ' + arguments[index]);
}
but that gives an error trying to get the interface:
java.lang.invoke.WrongMethodTypeException: Parameter counts differ:
(Object[])Object vs. (int,String[])void
Is this a deficiency in Nashorn's handling of variadic methods or am I
missing something here?
--
John
More information about the nashorn-dev
mailing list