2017-06-17 44 views
0

我是BeanShell的新手並學習它。目前,我有以下代碼將用戶輸入作爲字符串,然後使用BeanShell eval方法對其進行評估。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 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\");"; 

請幫忙。

回答

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