The Java String class (java.lang.String) contains quite a few useful methods that are not available for a Javascript String e.g. startsWith(), endsWith() etc. This post describes how to create a Java String object so these methods can be used.
For example, the following code will fail because the endsWith() function doesn't exist for a Javascript String:
Code: Select all
var s = "Hello World";
if (s.endsWith("World"))
Whereas this code will work:
Code: Select all
var s = new java.lang.String("Hello World");
if (s.endsWith("World"))
But there are some tricky corners that can be problematic. For example, you might expect the following code to work, but it doesn't:
Code: Select all
if (new java.lang.String("Hello World").toUpperCase().endsWith("WORLD"))
The problem is that the toUpperCase() method is returning a Java String but this is being converted by Rhino into a Javascript String. It then tries to invoke endsWith() on this Javascript String and fails. Whereas the following code works fine:
Code: Select all
if (new java.lang.String("Hello World".toUpperCase()).endsWith("WORLD"))
This appears very confusing at first sight, but there is some logic behind it. Every time something is accessed or returned from Java to Javascript, Rhino will look at the object and check if it should be converted to an equivalent Javascript type. This conversion is performed for all primitive types: String, Number, Boolean, plus the Date class plus Java arrays. Additionally, Java Collections - Lists, Map, Set etc - are converted to their equivalent Javascript types - arrays or objects - but this conversion is controlled by the Wrap Handler that is implemented and can be customized by implementing an alternative Wrap Handler (see parameter Ufs.rhinoWrapFactoryClassName in UFSSetup.properties).
Importantly, this type conversion is
not performed when the
new keyword is used, so:
Code: Select all
var s = new java.lang.String("Hello World");
produces a
Java String that has not been converted to a Javascript string. But:
produces a
Javascript String that has been converted.
These same principles can also be applied to other Java objects.