2

I'm trying to put all my Java methods accessible from a javascript script.

As I want "shortcuts", I followed the following guide: https://stackoverflow.com/a/19197130/2897090 . But when my Java method has variable arguments, I'm not able to "expose" the method to use with javascript language.

public void printf(String format, Object... args) {
    out.printf(format, args);
}
//Gives org.mozilla.javascript.EvaluatorException: Unsupported parameter type "[Ljava.lang.Object;" in method printf

Other thing:

If i try to make a "shortcut to the printf using just "javascript":

function printf(format){
    java.lang.System.out.printf(format, arguments);
}

If I type anything, I get org.mozilla.javascript.Arguments@NNNNNN. How to fix that?

Thank you.

Update

As I didn't find any solution, I changed the approach: now I'm just using the ScriptEngine. Practically what I'm doing is exposing the whole object (not just functions). Unfortunately every time that I need to call a function I need to prefix it with the name of the object that I've exposed.

Anyway, with that I could create my Java methods with variable arguments and use them without any modification on the JavaScript side.

Community
  • 1
  • 1

1 Answers1

0

I ran into this same problem. Since then they've updated the documentation on what a FunctionObject could be. It can only take a small set of data. Here was my solution:

@JSFunction
public void log(Object messages) {
    if(messages instanceof  List) {
        console.log(((List)messages).toArray());
    }
    else if (messages instanceof Object[]) {
        console.log(((Object[])messages));
    }
    else {
        console.log(new Object[]{messages});
    }
}

I wanted it to take an array of objects to print out. Instead I had to take an object, then use reflection to figure out if it was a list, array, or single object at runtime and provide appropriate handling.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127