Michael HönnigMichael Hönnig
Oft kommt man in Projekten in die Verlegenheit, Benutzer-definierte mathematische Funktionen zu berechnen, z.B. für einen Funktionsplotter. Solches lässt sich ohne große Umstände mit BeanShell erledigen:
import bsh.*;

/// Calculates y=f(x) with x, y € double   
public class Function {
        
    Interpreter interpreter = new Interpreter();
    {   
        try {                           
            interpreter.eval(
                    // add some shortcuts for math functions
                    "sin(a) { return Math.sin(a); } \n" +
                    "cos(a) { return Math.cos(a); } \n" +
                    "tan(a) { return Math.tan(a); } \n" +
                    "atan(a) { return Math.atan(a); } \n" );
        } catch (Exception e) {
            // this can not happen in production code
            e.printStackTrace();
        }       
    }   

    private String function;

    /// example: new Function("sin(x)+cos(x/3)/2")
    public Function(String function) {
        this.function = function;
    }   
        
    /// calculates y=f(x) using the function from the constructor
    double y(double x) throws EvalError {
        interpreter.set("x", x);
        interpreter.eval("y=" + function);
        return (Double) interpreter.get("y");
    }   
        
    /// example which prints y=f(x)=atan(x) from x in 0...9
    public static void main(String[] args) throws EvalError {
        
        Function f = new Function("atan(x)");
                
        for ( double x = 0; x < 10; ++x ) { 
            System.out.println("f("+x+") = " + f.y(x) ); 
        }       

    }   

}
In Maven2-basierten Build-Umgebungen kann BeanShell direkt aus einem Repository eingebunden werden, z.B. (auf aktuelle Version achten):
<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-script-beanshell</artifactId>
    <version>2.2.1</version>
</dependency>