国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

Java編程Nashorn實例代碼

2024-07-13 10:17:20
字體:
來源:轉載
供稿:網友

本文研究的主要是Java編程Nashorn的相關內容,具體如下。

Nashorn是什么

Nashorn,發音“nass-horn”,是德國二戰時一個坦克的命名,同時也是java/250230.html">java8新一代的javascript引擎--替代老舊,緩慢的Rhino,符合 ECMAScript-262 5.1 版語言規范。你可能想javascript是運行在web瀏覽器,提供對html各種dom操作,但是Nashorn不支持瀏覽器DOM的對象。這個需要注意的一個點。

之前學習Java8的時候恰好寫了個簡單的例子,所以放在這里記錄一下。

文件目錄:

  • StringFunction.java,字符串功能類
  • StringNashorn.java,封裝腳本引擎
  • NashornTest.java,測試引擎,引擎調用

StringFunction.java源碼:

public class StringFunction {      /**    * 字符串截取    */   public String sub(String str, int start, int end) {     return str.substring(start, end);   }      /**    * 字符串拼接    */   public String append(String... strs) {     StringBuilder result = new StringBuilder(strs[0]);     Stream.of(strs).skip(1).forEach(str -> result.append(str));     return result.toString();   } } 

StringNashorn.java源碼:

public class StringNashorn {      /**    * Nashorn腳本引擎    */   private ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");      /**    * 執行腳本    */   public Object execute(String script) {     ScriptContext scriptContext = new SimpleScriptContext();     // 定義一個名為stringfunction的函數,這個函數實際對應著一個StringFunction對象     scriptContext.setAttribute("stringfunction", new StringFunction(), 100);     nashorn.setContext(scriptContext);          Object result = null;     try {       result = nashorn.eval(script);     } catch (ScriptException e) {       e.printStackTrace();     }          return result;   } } 

NashornTest.java源碼:

public class NashornTest {      public static void main(String[] args) {     String substring = "stringfunction.sub(/"abcdefghijk/", 1, 4);";     String append = "stringfunction.append(/"abc/", /"def/");";          StringNashorn nashorn = new StringNashorn();     Object subResult = nashorn.execute(substring);     Object appendResult = nashorn.execute(append);     System.out.println(subResult.toString());     System.out.println(appendResult.toString());   } } 

運行main方法,運行結果:

bcd
abcdef

這里如果NashornTest.java改寫如下:

public class NashornTest {      public static void main(String[] args) {     // 腳本內用對象接收結果并打印     String substring = "var s1 = stringfunction.sub(/"abcdefghijk/", 1, 4);"         + " print(s1);";     String append = "var s2 = stringfunction.append(/"abc/", /"def/");"         + " print(s2);";          StringNashorn nashorn = new StringNashorn();     // 這里execute不再返回對象,因為在腳本里面已經有對象接收sub和append的執行結果。     nashorn.execute(substring);     nashorn.execute(append);   } } 

同樣也會輸出相同的結果。

總結

以上就是本文關于Java編程Nashorn實例代碼的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 清水河县| 赤水市| 左贡县| 盐池县| 蕉岭县| 凤山县| 金堂县| 淮北市| 高淳县| 咸阳市| 滕州市| 图木舒克市| 噶尔县| 察雅县| 绥阳县| 扎鲁特旗| 旌德县| 怀远县| 郁南县| 丰镇市| 凤城市| 吴桥县| 新密市| 班玛县| 临西县| 晋城| 海安县| 嘉峪关市| 洛宁县| 宁明县| 聂拉木县| 林口县| 洞口县| 楚雄市| 岐山县| 平远县| 甘泉县| 抚松县| 云南省| 扎赉特旗| 辰溪县|