Java Beanshell:在Beanshell中运行方法,而不使用类引用
我是比恩希尔的新手,正在学习。目前,我有以下代码以字符串形式获取用户输入,然后使用BeanShell评估方法对其进行评估Java Beanshell:在Beanshell中运行方法,而不使用类引用,java,beanshell,Java,Beanshell,我是比恩希尔的新手,正在学习。目前,我有以下代码以字符串形式获取用户输入,然后使用BeanShell评估方法对其进行评估 package beanshell; import bsh.EvalError; import bsh.Interpreter; public class DemoExample { public static void main( String [] args ) throws EvalError { Interpreter i = new
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\");";
请帮助。很酷,我们可以使用下面的反射来实现这一点
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");
}
}
packagebeanshell;
导入java.io.FileNotFoundException;
导入java.io.IOException;
导入java.lang.reflect.InvocationTargetException;
进口bsh.EvalError;
导入bsh.解释器;
公开课演示评估{
公共静态解释器i=新解释器();
publicstaticvoidmain(字符串[]args)抛出FileNotFoundException、IOException、EvalError、InstantiationException、IllegalAccessException、IllegalArgumentException、InvocationTargetException、NoSuchMethodException、SecurityException{
字符串userInput=“printValue()”;
对象结果=i.eval(“”)
+“公共类EvalUserInput扩展了beanshell.Demo_Eval{”
+“公共静态无效getUserInput(){”
+用户输入+“;”
+ "}"
+ "}");
类noparams[]={};
类别cls=(类别)结果;
Object obj=cls.newInstance();
getDeclaredMethod(“getUserInput”,noparams).invoke(obj,null);
}
公共静态void printValue(){
系统输出打印项次(“打印”);
}
}