• graalvm java map 参数传递js 方法调用


    因为js 有自己的特性,我们一般对于map 参数的传递通过ProxyObject.fromMap 处理,以下是一个demo

    基本使用

    • 参考代码
    public static  void es6Rollup2(Engine engine) throws IOException {
            Context context = Context.newBuilder().allowAllAccess(true).allowHostClassLoading(true).allowIO(true).allowNativeAccess(true).engine(engine).build();
            Source mysource = Source.newBuilder("js","load("src/main/resources/mydemoapp.js");","demoapp").mimeType("application/javascript+module").build();
            context.eval(mysource);
            Value callapp = context.getBindings("js").getMember("window");
            Value result = callapp.getMember("demo");
            Map<String,Object> ob =new HashMap<>();
            Map<String,Object> ob2 =new HashMap<>();
            ob2.put("url","https://plus.google.com/102817283354809142195/posts/F97fqZwJESL");
            ob.put("url","https://plus.google.com/102817283354809142195/posts/F97fqZwJESL");
            Map<String,Object> ob3 =new HashMap<>();
            ob3.put("url","https://plus.google.com/102817283354809142195/posts/F97fqZwJESL");
            ob2.put("ob",ProxyObject.fromMap(ob3));
            ob.put("id","z12gtjhq3qn2xxl2o224exwiqruvtda0i");
            ob.put("object",ProxyObject.fromMap(ob2));
            String filed = "url,object(url,ob/url)";
            System.out.println(ob.toString());
            String info ="{"id":"z12gtjhq3qn2xxl2o224exwiqruvtda0i","url":"https://plus.google.com/102817283354809142195/posts/F97fqZwJESL","object":{"objectType":"note","content":"A picture... of a space ship... launched from earth 40 years ago.","attachments":[{"objectType":"image","url":"http://apod.nasa.gov/apod/ap110908.html","image":{"height":284,"width":506}}]},"provider":{"title":"Google+"}}";
            Value execResult =result.execute(ProxyObject.fromMap(ob),filed);
            System.out.println(execResult);
        }
    • 说明
      通过ProxyObject处理,但是因为默认ProxyObject.fromMap 不会进行深复制处理,如果我们是嵌套的就需要多次处理
      同时以上的js 代码如下(使用了json-mask 处理json 内容,java 调用通过browserify 进行了转换,具体可以参考https://www.cnblogs.com/rongfengliang/p/13584488.html)
     
    const mask = require("json-mask")
    module.exports = {
        maskfn: function (datas, fields) {
            return mask(datas, fields)
        }
    }
    window = this || {}
    window.demo = function (datas, fields) {
        let mydatas 
        mydatas = datas;
        if (typeof datas === 'string') {
            mydatas =JSON.parse(datas)
        } 
        return mask(mydatas, fields)
    }
    • 运行效果

    说明

    实际上官方也有相关的特性开关,可以实现自动的处理,还没测试,后边测试下

    参考资料

    https://github.com/graalvm/graaljs/issues/143

  • 相关阅读:
    SpringMVC基础知识
    git pull 和git fetch的区别
    动态规划的原理?
    为什么要使用volatile修饰呢?
    内部类,匿名内部类?
    什么是性能优化?
    如何定位CPU瓶颈?
    什么是程序的耦合?
    什么是性能优化?
    Class类的常用方法?
  • 原文地址:https://www.cnblogs.com/rongfengliang/p/13585334.html
Copyright © 2020-2023  润新知