Mayday
Mayday

Reputation: 5146

How to convert array into multiple variables in java

Not duplicate question

As I stated downwards, I already checked how to work in java with different number of params. It wraps them into an array, and go ahead with it. But I need to pass different number of params to a function, not an array, since it will be treated with javascript


I am working with Nashorn in order to execute some javascript scripts in java. I am trying to modularize as much as possible the code, in order to be easy to use.

I have the following function to call a javascript method already:

MyClass{
....
    public static Object call(ScriptObjectMirror ctx, String functionName, Object ...args ) {
        ScriptObjectMirror caller = ctxs.get(ctx); // assume this works, it brings correct data
        return caller.call(ctx, functionName, args);
    }
....
}

So, I have read different questions like Can I pass an array as arguments to a method with variable arguments in Java?

Where it states clearly that Object... is the same as Object[].

However, when I am working on javascript side, I receive different things depending on the args:

Lets say I do the following call:

MyClass.call(myCtx, "a", true, false);

It will call:

caller.call(myCtx, "a", [true, false]); //Javascript prints: [Ljava.lang.Object;@273d3dbb

But, If I do skip the method MyClass.call in order to directly invoke javascript function like this:

caller.call(myCtx, "a", true, false); //Javascript prints true, false

THEREFOR

I can understand that java internally works fine with both (Object... and Object[]) BUT since I am using Nashorn, I really need to be able to get args, and split them.

Something like:

public static Object call(ScriptObjectMirror ctx, String functionName, Object ...args ) {
    //Pseudocode of what I want to achieve
    for (arg: args) {
        arg1 = arg;
        arg2 = arg;
        argN = arg;
    }
    return caller.call(ctx, functionName, arg1, arg2, ..., argN);

}

Is there any way to achieve this? / Any workaround?

NOTE

I can not just in javascript side assume I always receive an array with different arguments, since it can be called from a lot of different places, and would mean to recode really a lot of code

Upvotes: 0

Views: 1318

Answers (1)

Solomon Tam
Solomon Tam

Reputation: 739

You can't do exactly what Java could do, but you can do something similar.

Javascript function does support receive unlimited numbers of parameters. You can access the parameters by arguments keyword.

Please kindly read this.

For example:

function foo(){
    for(var i=0; i<arguments.length; i++){
  	    document.write(arguments[i] +'<br />');
    }
}

foo("A", "B", "C", 1, 2, 3);

Upvotes: 1

Related Questions