java 計算數學表達式及執行腳本語言


  java SE6中對常用的腳本語言做了支持。

  可供使用者在java代碼中執行腳本語言,還可以利用get("key"),put("key","value")與其交互,並可以動態調用腳本。

package com.test;

import java.util.List;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Demo {

    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        // 得到所有的引擎工廠
        List<ScriptEngineFactory> list = manager.getEngineFactories();
        for (ScriptEngineFactory factory : list) {
            System.out.println("支持的腳本語言"+factory.getNames());
            // 支持的腳本語言[js, rhino, JavaScript, javascript, ECMAScript, ecmascript]
        }
        
        // 得到常用的javascript腳本
        ScriptEngine engine = manager.getEngineByName("javascript");

        try {
            // 執行腳本
            System.out.println(engine.eval("2+3*2"));  // 8
            System.out.println(engine.eval("(true||false)&&true"));  //true
            
            // 和腳本交互
            engine.put("name", "123456");
            engine.eval("var out = '';" +
                        "for(i=0;i<name.length;i++){" +
                        "    out = name.charAt(i)+ out}");
            String name = (String)engine.get("out");
            System.out.println("name:"+name);
            
            // 動態調用腳本語言(腳本引擎得實現Invocable接口)
            String str = "abcdef";
            if(engine instanceof Invocable){
                engine.eval("function str1(name){" +
                        "var out = '';" +
                        "for(i=0;i<name.length;i++){" +
                        "    out = name.charAt(i)+ out}" +
                        "   return out;}" +
                        "function str2(name){" +
                        "    return 123}");
                
                Invocable invocable = (Invocable) engine;
                try {
                    Object obj = invocable.invokeFunction("str1", "123456");
                    System.out.println("obj:"+obj);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
            
            // 動態實現接口
            engine.eval("function run(){" +
                    "print('異步調用')}");
            Invocable invocable = (Invocable) engine;
            // 讓其實現Runnable接口
            Runnable runnable = invocable.getInterface(Runnable.class);
            // 啟動線程
            Thread t = new Thread(runnable);
            t.start();
        
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        
        
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM