美文网首页
JavaScript的调用

JavaScript的调用

作者: 手打小黑板 | 来源:发表于2020-02-12 10:17 被阅读0次
    package com.liming.script;
    
    import javax.script.*;
    import java.io.*;
    import java.net.URI;
    import java.net.URL;
    import java.net.URLClassLoader;
    import java.util.Arrays;
    import java.util.List;
    
    public class ScriptTest {
    
    
        public static void main(String[] args){
            System.out.println("Hello JavaScript");
    
            ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
            ScriptEngine hehe = scriptEngineManager.getEngineByName("javascript");
    
            hehe.put("name","林立");
            String evalStr = "var t = '你是谁';";
                evalStr += "var user = {a:'kkk',b:123,c:['qqq','www','eee']};";
            evalStr += "name='胖虎';var arr = user.a;";
    
            try {
                hehe.eval(evalStr);
                System.out.println(hehe.get("arr"));
                System.out.println(hehe.get("name"));
    
                hehe.eval("function add(a,b){ return a+b+''+3453455;}");
    
                Invocable jsInvoke = (Invocable)hehe;
                Object o = jsInvoke.invokeFunction("add",1,2);
                System.out.println(o);
    
    
                hehe.eval("var last = java.util.Arrays.asList([\"大雄\",\"胖虎\",\"小夫\"]);");
               // List<String> ls = Arrays.asList(new String[]{"大雄","胖虎","小夫"});
    
                List<String> list = (List<String>)hehe.get("last");
                for (String s :
                        list) {
                    System.out.println(s);
                }
    
                URL url = ScriptTest.class.getClassLoader().getResource("test.js");
    
                hehe.eval(new FileReader(new File(url.getFile())));
    
                ((Invocable) hehe).invokeFunction("add");
                System.out.println(url.getPath());
                System.out.println(url.getFile());
    
    
    
            } catch (ScriptException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    
    
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:JavaScript的调用

          本文链接:https://www.haomeiwen.com/subject/pxuqfhtx.html