It's possible to pass Java objects to Nashorn engine to be processed in Java code. At the same time, there are some JavaScript (and Nashorn) specific constructions, and it's not always clear how they work with java objects.
Below there is a table which describes behaviour of native Java objects inside JavaScript constructions.
Tested constructions:
Results:
Type | If | for each | .length |
---|---|---|---|
Java null | false | No iterations | Exception |
Java empty string | false | No iterations | 0 |
Java string | true | Iterates over string characters | Length of the string |
Java Integer/Long | value != 0 | No iterations | undefined |
Java ArrayList | true | Iterates over elements | Length of the list |
Java HashMap | true | Iterates over values | null |
Java HashSet | true | Iterates over items | undefined |
Recommendatons:
if (some_string)
to check if a string is not null and not emptyfor each
can be safely used to iterate over any collection, and it doesn't raise exceptions if the collection is not iterable, null or undefined