首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Nashorn 進階(六):JavaScript 語法擴展與 JVM 字節碼編譯

     編輯:Java 相關知識

Nashorn 的 JS 語法擴展(基於 Mozilla 方言)

1. foreach 循環

標準 JS 無 foreach,Nashorn 支持 Mozilla 風格:


var jsEngs = ["Nashorn", "Rhino", "V8", "IonMonkey", "Nitro"];
for each (js in jsEngs) {
    print(js);
}

2. 單表達式函數簡寫

函數體僅一個表達式時,可省略大括號和 return:


function cube(x) x*x*x;       // 合法於 Nashorn
function cube2(x) { return x*x*x; } // 標準寫法
print(cube(3));   // 27
print(cube2(3));  // 27

3. 多 catch 子句

標準 JS 僅支持單一 catch,Nashorn 引入 Mozilla 擴展支持類型過濾:


function fnThatMightThrow() {
    if (Math.random() < 0.5) throw new TypeError();
    else throw new Error();
}
try {
    fnThatMightThrow();
} catch (e if e instanceof TypeError) {
    print("Caught TypeError");
} catch (e) {
    print("Caught some other error");
}
注意:JS 中所有異常均為 unchecked 類型。

實現細節:直接編譯為 JVM 字節碼

Nashorn 將 JS 代碼直接編譯為字節碼並執行,從不解釋執行。Lambda 表達式可作為函數實現 Java 函數式接口。

示例:實現 Callable 接口


jjs> var clz = Java.type("java.util.concurrent.Callable");
jjs> var obj = new clz(function () { print("Foo"); });
jjs> print(obj);
// 輸出: jdk.nashorn.javaadapters.java.util.concurrent.Callable@290dbf45

動態生成的適配器類名包含接口全名,可讀性強。靜態代碼生成是 Nashorn 核心機制。

ECMAScript 合規性限制

因嚴格遵循 ECMAScript 5.1 規範,print({foo:"bar"}) 僅輸出 [object Object],無法顯示對象詳細屬性(規範強制要求)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved