Using .apply () for a Java method from rhino (JavaScript)

I want to use rhino (JavaScript) function.apply() to pass arguments to the Java varags method, something like this:

 function sprintf() { return java.lang.String.format.apply(arguments); } sprintf("%d\n", 5); 

But calling sprintf() gives an error:

 Error: can't find method java.lang.String.format(). 

I suppose this is because the format() method is not a proper JavaScript function, but a Java method, so it does not have apply() . (Although this is not what the error message seems to be, maybe not.)

I found that I can add my own apply () method:

 java.lang.String.format.apply = function() {} 

But I don’t see how to write apply() without apply() , if you understand what I mean. Any ideas?

+4
source share
2 answers

@ Vincent Montressor

Here is a partial solution:

 function sprintf(string) { var args = Array.prototype.splice.call(arguments, 1); for (var i = 0; i < args.length; i++) { if (!isNaN(args[i])) { args[i] = new java.lang.Integer(args[i]); } } return java.lang.String.format(String(string), args); } 

There are several problems:

  • In your implementation of .format (), the method signature is not used properly, i.e. the first parameter must be a string
  • The numeric values ​​in the argument list must be converted to the corresponding java types.

Here is an example call:

 print(sprintf("Hello %s %d", "number", 2)); 

What produces: "Hello number 2"

+1
source

Is java.lang that you are not using the "format" {method} in the String . If String.format is found, use:

  format("Hello, %s!", [firstName]); 

you format the strring create sprintf function

 function sprintf() { return String.format.apply(arguments); } 

In my opinion, use the format () function ...

0
source

Source: https://habr.com/ru/post/1438920/


All Articles