bsh(BeanShell)动态执行java代码 博客分类: java bsh
程序员文章站
2024-03-17 12:42:40
...
import java.util.Date;
/**
* BeanShell解释器:亦可嵌入到JAVA源代码中,能动态执行JAVA源代码 bsh-1.3.0.jar
*/
public class IfTest {
public static void main(String[] args) {
Interpreter interpreter = new Interpreter();
String s = "2>3||3>4&&5<4";
try {
//计算表达式
interpreter.set("boolean", interpreter.eval("(" + s +")"));
System.out.println(interpreter.get("boolean"));
interpreter.set("foo", 5);
interpreter.set("date", new Date() );
Date date = (Date)interpreter.get("date");
interpreter.eval("bar = foo*10");
System.out.println(interpreter.get("bar") );
//interpreter.source("somefile.bsh");
interpreter.eval("for(int i=0; i<3; i++) { System.out.println(\"ni hao!\"); }");
s="1>2";
Object result=interpreter.eval(s);
System.out.println(result);
interpreter.eval("import java.text.*;");//引入text
Object r1=interpreter.eval("SimpleDateFormat.getDateInstance().format(new Date())");//执行SimpleDateFormat类的format()方法
System.out.println(r1);
Object r2=interpreter.eval("SimpleDateFormat.getDateInstance().format(date)");// 使用date变量
System.out.println(r2);
interpreter.set("status", "send");
Object obj = interpreter.eval("status == \"send\" && 1>0");
System.out.println(obj);
} catch (EvalError e) {
e.printStackTrace();
}
}
}
/**
* BeanShell解释器:亦可嵌入到JAVA源代码中,能动态执行JAVA源代码 bsh-1.3.0.jar
*/
public class IfTest {
public static void main(String[] args) {
Interpreter interpreter = new Interpreter();
String s = "2>3||3>4&&5<4";
try {
//计算表达式
interpreter.set("boolean", interpreter.eval("(" + s +")"));
System.out.println(interpreter.get("boolean"));
interpreter.set("foo", 5);
interpreter.set("date", new Date() );
Date date = (Date)interpreter.get("date");
interpreter.eval("bar = foo*10");
System.out.println(interpreter.get("bar") );
//interpreter.source("somefile.bsh");
interpreter.eval("for(int i=0; i<3; i++) { System.out.println(\"ni hao!\"); }");
s="1>2";
Object result=interpreter.eval(s);
System.out.println(result);
interpreter.eval("import java.text.*;");//引入text
Object r1=interpreter.eval("SimpleDateFormat.getDateInstance().format(new Date())");//执行SimpleDateFormat类的format()方法
System.out.println(r1);
Object r2=interpreter.eval("SimpleDateFormat.getDateInstance().format(date)");// 使用date变量
System.out.println(r2);
interpreter.set("status", "send");
Object obj = interpreter.eval("status == \"send\" && 1>0");
System.out.println(obj);
} catch (EvalError e) {
e.printStackTrace();
}
}
}