Rhino: How to get all properties from ScriptableObject?
Asked Answered
C

2

5

I am using a Javascript object as an object with configuration properties. E.g. I have this object in javascript:

var myProps = {prop1: 'prop1', prop2: 'prop2', 'prop3': 'prop3'};

This object (NativeObject) is returned to me in Java function. E.g.

public Static void jsStaticFunction_test(NativeObject obj) {
    //work with object here
}

I want to get all properties from object and build HashMap from it.

Any help will be appreciated.

Cenobite answered 1/4, 2010 at 9:42 Comment(0)
R
2

well, if you looked closer, you would have seen that NativeObject implements the Map interface, so you could have worked very well with the NativeObject.... But to answer your question: you could have used the common approach for getting the key-value pairs of any map

for (Entry<Object, Object> e : obj.entrySet()){
   mapParams.put(e.getKey().toString(), e.getValue().toString());
}

A cast would have been enough for your case, because you have only strings as values. So, if you really wanted a HashMap:

HashMap<String, String> mapParams = new HashMap<String, String>((Map<String,String>)obj); //if you wanted a HashMap

But if you just wanted a generic Map, it was even simpler, and less RAM consuming:

Map<String, String> mapParams = (Map<String,String>)obj;
Rudiger answered 30/5, 2012 at 10:55 Comment(0)
C
10

So, I solved my problem :)

Code:

public static void jsStaticFunction_test(NativeObject obj) {
    HashMap<String, String> mapParams = new HashMap<String, String>();

    if(obj != null) {
        Object[] propIds = NativeObject.getPropertyIds(obj);
        for(Object propId: propIds) {
            String key = propId.toString();
            String value = NativeObject.getProperty(obj, key).toString();
            mapParams.put(key, value);
        }
    }
    //work with mapParams next..
}
Cenobite answered 1/4, 2010 at 10:21 Comment(0)
R
2

well, if you looked closer, you would have seen that NativeObject implements the Map interface, so you could have worked very well with the NativeObject.... But to answer your question: you could have used the common approach for getting the key-value pairs of any map

for (Entry<Object, Object> e : obj.entrySet()){
   mapParams.put(e.getKey().toString(), e.getValue().toString());
}

A cast would have been enough for your case, because you have only strings as values. So, if you really wanted a HashMap:

HashMap<String, String> mapParams = new HashMap<String, String>((Map<String,String>)obj); //if you wanted a HashMap

But if you just wanted a generic Map, it was even simpler, and less RAM consuming:

Map<String, String> mapParams = (Map<String,String>)obj;
Rudiger answered 30/5, 2012 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.