我有一个javascript脚本,在评估时会返回一个NativeObject
obj = context.evaluateString(scope,"({age:3, name:'bob'})", "<source">, 1, null)
然后我将obj转换为NativeObject或Map,然后运行put方法
castObj.put("surname","smith")
我得到一个java.lang.UnsupportedOperationException抛出。还有其他方法可以更改对象值吗?
答案 0 :(得分:3)
您应该调用NativeObject.put(String, Scriptable, Object)
版本,而不是put(String, Object)
接口继承的Map
:
public class AddPropertyToObject {
public static void main(String[] args) {
new ContextFactory().call(new ContextAction(){
@Override
public Object run(Context ctx) {
Scriptable scope = ctx.initStandardObjects();
try {
Scriptable entity = ctx.newObject(scope);
NativeObject result = (NativeObject) ctx.evaluateString(
scope,
"({age:3, name:'bob'})",
"<inline>", 1, null);
result.put("surname", result, "Smith");
for (Entry<Object, Object> p : result.entrySet()) {
System.out.println(p.getKey() + ": " + p.getValue());
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
return null;
}
});
}
}