隨著java
案例
例
import java
import javax
import javax
import javax
import javax
/**
author by ?id=
*/
public class RunScript {
public static void main(String[] args) throws IOException{
ScriptEngineManager scriptManager = new ScriptEngineManager();//得到解釋器的管理器
ScriptEngine js = scriptManager
//定義我們要運行的腳本文件
String filename = null;
//通過解釋器來獲得存儲javascript變量的Bindings的實例
Bindings bindings = js
//處理參數
for(int i =
String arg = args[i];
if(arg
int pos = arg
if(pos ==
String name=arg
String value= arg
//注意
bindings
}else{
if(filename!=null)usage();
filename=arg;
}
}
//這裡是為了確保我們得到了一個文件的參數
if(filename==null){
usage();
}
//增加一個具有約束力的使用特殊的保留變量名稱
bindings
//讀取文件的流
Reader in = new FileReader(filename);
try{
//執行腳本並取得結果
Object result = js
System
}catch(ScriptException ex){
//執行過程中出異常則顯示一個錯誤信息
System
}
}
static void usage(){
System
System
}
}
這段代碼中所創建的Bindings對象不是靜態的
import javax
import java
import java
/**
author by ;
*/
//這個類像java
public class Configuration {
Map<String
//在map中獲取和設置值的方法
public Object get(String key){
return defaults
}
public void put(String key
defaults
}
//從map的name/value對中獲取初始化內容
public void load(String filename) throws IOException
//獲得javascript編譯器
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager
//使用我們的name/value對(即javascript變量)
Bindings bindings = new SimpleBindings(defaults);
//創建一個變量
ScriptContext context = new SimpleScriptContext();
//設置那些Bindings 在Context 中
context
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while((line=in
line = line
if(line
if(line
int pos = line
if(pos ==
throw new IllegalArgumentException(
}
String name = line
String value= line
char firstchar = value
int len = value
char lastchar = value
if(firstchar==
//雙引號引用的值為字符串
defaults
}else if(Character
//如果開始是一個數字
try{
double d = Double
defaults
}catch (NumberFormatException e) {
//沒有數字
defaults
}
}else if(
defaults
}else if(
defaults
}else if(
defaults
}else if(firstchar==
//如果值是在一對大括號之內
String script = value
Object result = engine
defaults
}else{
//其它情況
defaults
}
}
}
//一個簡單的類的測試程序
public static void main(String[] args) throws IOException
Configuration defaults = new Configuration();
defaults
Set<Map
for(Map
System
}
}
}
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19250.html