在 BeanShell 的帮助下在嵌入式代码中调用方法

call method in embedded code with the help of BeanShell

我需要在我的代码中调用一些 java 代码。我为此使用 BeanShell。 所以,我可以这样做:

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

但是如果我想在解释器中调用其他方法怎么办?我想要这样的东西:

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

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

但是我遇到了一个错误 "Command not found"

将 class 的实例设置为解释器上的变量:

    i.set("instance", this);
    i.eval("instance.testMethod()");

我终于找到了解决办法。

我正在使用 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();

现在我们有了 Class2 的实例。请注意,新的 Class2 应该扩展现有的 Class1,我们只能调用 Class1 中声明的方法。

检查是否对您有帮助。

package beanshell;

import bsh.EvalError;
import bsh.Interpreter;

public class DemoExample {

    public static void main( String [] args ) throws EvalError  {
        Interpreter i = new bsh.Interpreter();
        String usrIp = "if(\"abc\".equals(\"abc\")){"
                + "demoExmp.printValue(\"Rohit\");"
                + "}";

        i.eval(""
                + "import beanshell.DemoExample;"
                + "DemoExample demoExmp = new beanshell.DemoExample();"
                + ""+usrIp);
    }

    public static void printValue(String strVal){
        System.out.println("Printing Value "+strVal);
    }
}

尝试以下:

package beanshell;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import bsh.EvalError;
import bsh.Interpreter;

public class Demo_Eval {
    public static Interpreter i = new Interpreter();

    public static void main(String[] args) throws FileNotFoundException, IOException, EvalError, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
        String userInput = "printValue()";

        Object result = i.eval(""
                + "public class EvalUserInput extends beanshell.Demo_Eval{"
                + "public static void getUserInput(){"
                + userInput+";"
                + "}"
                + "}");

        Class<?> noparams[] = {};
        Class cls = (Class) result;
        Object obj = cls.newInstance();
        cls.getDeclaredMethod("getUserInput", noparams).invoke(obj, null);
    }

    public static void printValue(){
        System.out.println("Printed");
    }
}