software-mariodiana
6/1/2016 - 7:31 PM

Example of how to incorporate BeanShell into an application to evaluate strings as Java code.

Example of how to incorporate BeanShell into an application to evaluate strings as Java code.

// http://www.beanshell.org/manual/bshmanual.html#Calling_BeanShell_From_Your_Application
import bsh.EvalError;
import bsh.Interpreter;

import java.util.regex.*;

/**
 * Hello, BeanShell!
 * 
 * <!-- http://mvnrepository.com/artifact/org.beanshell/bsh -->
 * <dependency>
 *     <groupId>org.beanshell</groupId>
 *     <artifactId>bsh</artifactId>
 *     <version>2.0b5</version>
 * </dependency>
 *
 */
public class App {
    public static void main( String[] args ) throws EvalError {
        Interpreter i = new Interpreter();
        
        i.eval("String greeting = \"Hello, BeanShell!\"");
        String greeting = (String)i.get("greeting");
        
        System.out.println(greeting);
        
        i.eval("import java.util.regex.Pattern");
        i.eval("Pattern p = Pattern.compile(\"hello\", Pattern.CASE_INSENSITIVE)");
        Pattern p = (Pattern)i.get("p");
        
        System.out.println(p.matcher("hello").find());
        System.out.println(p.matcher("Hello").find());
        System.out.println(p.matcher("goodbye").find());
    }
}