Rhino - Scriptable method: Object get (String name, Scriptable start) not finding the correct key (numeric string)

StackOverflow https://stackoverflow.com/questions/23284998

  •  09-07-2023
  •  | 
  •  

Question

I'm using Rhino to parse a javascript object into my Java application and I wish to understand about the behavior of the get method of the Scriptable object.

My javascript object is similar to this:

Obj = {};
Obj['001'] = 'First Content';
Obj['100A'] = 'Second Content';
Obj['100'] = 'Third Content';

As it is stated in the documentation, I should be using the signature that takes an integer and the Scriptable start.

JavaScript code | Java code

a[3] | a.get(3, a)

a["3"] | a.get(3, a)

My question is this: Why the signature that takes the String argument cant match the numeric string?

Is my solution correct or there would be a way to just use the (String name, Scriptable start) signature?

// Scriptable scope already defined
// id is an object from scope.getIds()
Scriptable content;

if(id instanceof Integer) {
    content = scope.get((Integer) id, scope);
} else {
    content = scope.get((String) id, scope);
}

Thank You

Rhino 1.7R2

Was it helpful?

Solution

I realize this doesn't explicitly address your question (which is that you want to understand), but I wanted to recommend that you just decide not to understand.

Just implement Scriptable.get(int,Scriptable) like this:

Object get(int index, Scriptable start) {
  return this.get(String.valueOf(index),start);
}

... and stop worrying about it. This strange double-API for property access probably existed for some ancient performance reason. Remember, Rhino's roots are very old, going back to when Netscape (!) tried to rewrite Netscape Navigator (!) in Java. There is no distinction between numeric and other properties in the JavaScript standards, so in my view you're better off matching the language's behavior in your objects and not worrying about Rhino's idiosyncrasies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top