5

我使用 Javascript 对象作为具有配置属性的对象。例如,我在 javascript 中有这个对象:

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

这个对象 (NativeObject) 在 Java 函数中返回给我。例如

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

我想从对象中获取所有属性并从中构建 HashMap。

任何帮助将不胜感激。

4

2 回答 2

10

所以,我解决了我的问题:)

代码:

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..
}
于 2010-04-01T10:21:09.823 回答
2

好吧,如果您仔细观察,您会看到 NativeObject 实现了 Map 接口,因此您可以很好地使用 NativeObject...。但是要回答您的问题:您可以使用通用方法来获取密钥-任何映射的值对

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

对于您的情况,强制转换就足够了,因为您只有字符串作为值。所以,如果你真的想要一个 HashMap:

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

但如果你只想要一个通用的 Map,它会更简单,而且 RAM 消耗更少:

Map<String, String> mapParams = (Map<String,String>)obj;
于 2012-05-30T10:55:29.567 回答