cocoon-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jason Johnston <>
Subject Re: Java strings vs. Javascript strings
Date Tue, 28 Aug 2007 01:05:14 GMT
Tobia Conforto wrote:
> Jason Johnston wrote:
>> Rhino also makes the JavaScript methods available to Java strings if
>> the java.lang.String class doesn't already define them. For example:
>>    js> javaString.match(/a.*/)
> Thanks, that clears part of the confusion to me.
> It also explains why sometimes I could get away with treating strings
> as the language (JavaScript) calls for, while other times I couldn't.
> For example match() works the same on both string types, as the example
> says, while replace() doesn't.  That's just great.
> To complicate matters further, I cannot simply wrap a java.lang.String
> in a JS String() constructor and call replace() on the resulting object,
> because whenever I handle a java.lang.String I must expect to receive a
> Java null, but that becomes a JS null, and String(null) == 'null'!
> So:
> 	null is false
> 	"" is false
> 	java.lang.String("") is true (!)
> 	String(java.lang.String("")) is false
> 	String(null) is true

Yeah that's definitely not fun. :-)

So digging around in the Rhino API I discovered the WrapFactory 
class[1], which is what Rhino uses to wrap Java objects returned from 
methods so that they can be scripted.  By default it wraps 
java.lang.String objects just like it wraps any other Java object, 
giving your script access to its Java methods.  But it does allow you to 
switch this behavior for "primitive" values (strings, numbers, 
booleans), so that it exposes them as native JavaScript primitives e.g. 
the JavaScript String.

You can flip that switch by adding the following line to your flowscript:;

At least in my limited testing this seems to cause any Java String 
values returned from methods to be treated as JavaScript String 
primitives.  For example the replace() method works just fine and it 
shouldn't have the issues with nulls you mentioned earlier.

Give it a try, hope it works for you.


To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message