[英]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);
}
}
但是期望是-用戶不應提供類引用,並且代碼應運行良好。 因此用戶輸入值如下:
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");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.