Java动态执行代码Bsh

 

首先要到http://www.beanshell.org/download.html去下载个BeanShell的一个包,如bsh-2.0b4.jar ,然后在ClassPath中将它的地址加上.

package test;

import java.util.Date;
import bsh.EvalError;
import bsh.Interpreter;

public class Test {
 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"));
  } catch (EvalError e) {
   e.printStackTrace();
  }
 }
}

 

从你的应用程序调用BeanShell

 

通过建立一个BeanShell解释器,使用eval()或source()命令,你可以在你的应用程序中求文本表达式的值和运行脚本。如果你希望在你的脚本内部使用一个对象,可以用set()方法传递对象的变量参数给BeanShell,并通过get()方法取得结果。

   

 import bsh.Interpreter;
    Interpreter i = new Interpreter();  // Construct an interpreter
    i.set("foo", 5);                    // Set variables
    i.set("date", new Date() );
    Date date = (Date)i.get("date");    // retrieve a variable
    // Eval a statement and get the result
    i.eval("bar = foo*10");            
    System.out.println( i.get("bar") );
    // Source an external script file
    i.source("somefile.bsh"); 

 

如官方的例子

         Here are some examples:

 

                Interpeter bsh = new Interpreter();

                // Evaluate statements and expressions
                bsh.eval("foo=Math.sin(0.5)");
                bsh.eval("bar=foo*5; bar=Math.cos(bar);");
                bsh.eval("for(i=0; i<10; i++) { print(\"hello\"); }");
                // same as above using java syntax and apis only
                bsh.eval("for(int i=0; i<10; i++) { System.out.println(\"hello\"); }");

                // Source from files or streams
                bsh.source("myscript.bsh");  // or bsh.eval("source(\"myscript.bsh\")");

                // Use set() and get() to pass objects in and out of variables
                bsh.set( "date", new Date() );
                Date date = (Date)bsh.get( "date" );
                // This would also work:
                Date date = (Date)bsh.eval( "date" );

                bsh.eval("year = date.getYear()");
                Integer year = (Integer)bsh.get("year");  // primitives use wrappers

                // With Java1.3+ scripts can implement arbitrary interfaces...
                // Script an awt event handler (or source it from a file, more likely)
                bsh.eval( "actionPerformed( e ) { print( e ); }");
                // Get a reference to the script object (implementing the interface)
                ActionListener scriptedHandler = 
                        (ActionListener)bsh.eval("return (ActionListener)this");
                // Use the scripted event handler normally...
                new JButton.addActionListener( script );
        

 

你可能感兴趣的:(java)