Java-Beanshell:运行 来自 beanshell 的方法,没有 class 引用

Java-Beanshell: Run methods from within beanshell without class reference

我是 BeanShell 的新手,正在学习它。目前,我有以下代码将用户输入作为字符串获取,然后使用 BeanShell eval 方法对其进行评估。

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 = "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);
    }
}

但期望是 - 用户不应提供 class 参考,代码应该 运行 没问题。所以用户输入值如下:

String usrIp = "printValue(\"Rohit\");";

请帮忙。

太棒了,我们可以使用反射来实现,如下所示。

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");
    }
}