• Latest Code...

    Convert String to Code at runtime in Java

    In many case if you god string and that doesnot work fro checking logical condition then you may have to convert to code and use it.

    One option is using BeanShell: BeanShell Offical key class is bsh.Interpreter.

    Download BeanShell ->> http://www.beanshell.org/download.html

    if you download successfully  above bsh jar file. then import it>

    1. Right Click to Project
    2. Go to Java Build Path
    3. Click Library tab
    4. Click External Library file and select bash.jar  and refresh project.

    import bsh.EvalError;
    import bsh.Interpreter;

    public class Ohs {

    public static void main(String[] args) {
    String log1 = "10>=7";
    String log2 = "10<=7";
    Interpreter interpreter = new Interpreter();
    try{
    Object res = interpreter.eval(log1);
    System.out.println("Output1---"+log1+"-->>"+res.toString());

    Object res1 = interpreter.eval(log2);
    System.out.println("Output2---"+log2+"-->"+res1.toString());
    }catch (EvalError e1){
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }
    }


    }


    Output Looks Like:

    Output1---10>=7-->>true
    Output2---10<=7-->false

    Others methods of Converting String to Code in Java:

    Circle

    Most recent Elastic Search tutorials for beginner, intermediate and advance level developer, Yubraj Pokharel, in CodingWorkspace