Using Java reflection to create eval() method

后端 未结 4 554
-上瘾入骨i
-上瘾入骨i 2020-12-10 19:00

I have a question about reflection I am trying to have some kind of eval() method. So i can call for example:

eval(\"test(\'woohoo\')\");

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 19:35

    Ok thanxs to all the people who answered my question here the final solution:

    import java.lang.reflect.Method;
    public class Main {
       public static void main(String[] args){
          String func = "test";
          Object arguments[] = {"this is ", "really cool"};
          try{
             Class cl = Class.forName("Main");
             for (Method method : cl.getMethods()){
                if(method.getName().equals(func)){
                   method.invoke(null, arguments);
                }
              }
           } catch (Exception ioe){
              System.out.println(ioe);
           }
        }
      public static void test(String s, String b){
         System.out.println(s+b);
      }
    }
    

提交回复
热议问题