Rhino and Java UnaryOperator

101 views
Skip to first unread message

Nicola Attico

unread,
Jun 5, 2021, 1:51:53 AM6/5/21
to mozilla-rhino
Hi Everyone,
I'm using Rhino within ServiceNow to call a Java API from Javascript
This API requires to pass Lambda functions

This is an example:
identityNetwork.createDidTransaction(DidMethodOperation.CREATE) .setDidDocument(didDocument)
.signDidDocument(doc -> didRootKey.sign(doc))
.buildAndSignTransaction(tx -> tx.setMaxTransactionFee(new Hbar(2))
.build(client))
.onDidDocumentReceived(msg -> { System.out.println("DID document published!"); System.out.println(msg.getDidDocument()); })
.execute(client, client);

How can I pass these parameters from Javascript to Java? In the code, they're of type UnaryOperator.
I'm able to create an UnaryOperator of type identity

UnaryOperator = Packages["java"]["util"]["function"]["UnaryOperator"]
var x = UnaryOperator.identity()
for (i in x) {ms.log(i)}
ms.log(x)

*** Script: compose
*** Script: apply
*** Script: andThen
*** Script: java.util.function.UnaryOperator$$Lambda$155/229566071@7bc9a68f

but I don't see how to create it with my own function.
I've Rhino 1.7R5.

Thanks
Nicola

Tony Germano

unread,
Jun 9, 2021, 7:38:59 PM6/9/21
to mozilla-rhino
That's an old version of Rhino, but this document may help:
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scripting_Java#implementing_java_interfaces

Here's an example on how to create your own UnaryOperator. In a nutshell, you create a JavaScript object with function properties whose names match the methods required by the Java interface. Then you create a new instance as if the interface were a class with a constructor and pass it your object that implements the interface.

UnaryOperator = Packages["java"]["util"]["function"]["UnaryOperator"]
var x = new UnaryOperator({apply: function(i) {return Number(i) + 1}})
var result = x.apply(3) // this returns a java.lang.Double with a value of 4.0
var isUnaryOperator = (x instanceof UnaryOperator) // true

A warning -- in your version of Rhino, this will let you implement the interface, and the apply method will work, but the default methods are not implemented correctly. Calls to "andThen" or "compose" will return null instead of another UnaryOperator. If this matters in your situation, you may need to define those methods as well as "apply."

Tony
Reply all
Reply to author
Forward
0 new messages