我有一个JavaScript脚本,该脚本在评估时返回NativeObject

obj = context.evaluateString(scope,"({age:3, name:'bob'})", "<source">, 1, null)


然后,我将obj转换为NativeObject或Map,然后运行put方法

castObj.put("surname","smith")


而且我抛出了java.lang.UnsupportedOperationException。有没有其他方法可以更改对象值?

最佳答案

您应该调用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;
            }
        });
    }
}

09-12 05:45