Javaμ???±??ˉì?ó?·¨
ê±??:2011-01-05
function??doSth(){
jf.setSize(500,300);
jf.setVisible(true);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
}
function??getNames(){
list.add("doSth");
list.add("getNames");
return??list;
}
function??testJS(){
print(''Hello??world!'');
}
import??java.io.FileReader;
import??java.util.ArrayList;
import??java.util.List;
import??javax.script.Bindings;
import??javax.script.Invocable;
import??javax.script.ScriptContext;
import??javax.script.ScriptEngine;
import??javax.script.ScriptEngineManager;
import??javax.swing.JFrame;
/**
*
*??@author??hadeslee
*/
public??class??Test??{
public??static??void??main(String[]??args)throws??Exception??{
//?ù?Yjsμ?oó×o??éú3éò????a??JSμ???±??a??òy??
ScriptEngine??engin=new??ScriptEngineManager().getEngineByExtension("js");
//2é?ˉò????a??òy??ê?·?êμ??á?????oüêμó?μ??ó?ú
System.out.println(engin??instanceof??Invocable);
//éù?÷á??????ó£?′?è?μ?JSà???è¥
JFrame??jf=new??JFrame("test");
List<String>??list=new??ArrayList<String>();
//μ?μ?’2?¨μ??ü?μ???ó£?°?μ±?°μ?á???JAVA???ó·???è¥
Bindings??bind=engin.createBindings();
bind.put("jf",jf);
bind.put("list",list);
//°?’2??μ??ü?μ???ó·???襣?×÷ó?óòê?μ±?°òy??μ?·??§
engin.setBindings(bind,ScriptContext.ENGINE_SCOPE);
//ó?òy???′DDò???D′?úJS???tà???μ?′ú??
Object??obj=engin.eval(new??FileReader("test.js"));
//?a??ê±oò·μ???μμ±è???ê?nullá?
System.out.println(obj);
//°?μ±?°μ?òy??????×a?aInvocable£??a?ù?í?éò?μ÷ó??¨ò??úJS???tà???μ?ò???ò???oˉêyá?
Invocable??in=(Invocable)engin;
//μ?μ?á?′óJSà???·μ??à′μ????ó
List<String>??l=(List<String>)in.invokeFunction("getNames");
System.out.println(l);
//μ÷ó?ò????¨ò??úJSà???μ?áíò???oˉêy
in.invokeFunction("testJS");
//×?oóμ÷ó?ò???oˉêy£???oˉêy?éò?ê1?ò???°???¨ò?μ?′°ì???ê?3?à′
in.invokeFunction("doSth");
}
}
|