Java-Beanshell:在没有类引用的情况下从beanshell中运行方法

时间:2017-06-17 11:57:48

标签: java beanshell

我是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);
    }
}

但期望是 - 用户不应该提供类引用,代码应该运行正常。所以用户输入值如下:

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

请帮忙。

1 个答案:

答案 0 :(得分:0)

很酷,我们可以使用如下反射实现这一点。

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