Search code examples
javabeanshell

call method in embedded code with the help of BeanShell


I need to call some java code in my code. I use BeanShell for it. So, I can do this:

public void testInterpreter() {
    Interpreter i = new Interpreter();
    i.eval("System.out.println("test1"));
}

But what if I want to call other method in interpreter? I want something like that:

public void testInterpreter() {
    Interpreter i = new Interpreter();
    i.eval("testMethod()");
}

public void testMethod() {
    System.out.println("test2")
}

But I'm getting an error "Command not found"


Solution

  • Finally I've found the solution.

    I'm using Janino Compiler (http://unkrig.de/w/Janino)

    String javaClass = "code of new java Class2 that extends existing Class1";
    SimpleCompiler sc = new SimpleCompiler();
    sc.cook(javaClass);
    Class<?> executeClass = sc.getClassLoader().loadClass("Class2");
    
    Class1 instance = (Class1) executeClass.getConstructor().newInstance();
    

    Now we have an instance of our Class2. Note that new Class2 should extend existing Class1 and we can call only methods declared in Class1.