Using Java reflection to create eval() method

后端 未结 4 529
-上瘾入骨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:16

    You will need to call Class.getMethods() and iterate through them looking for the correct function.

    For (Method method : clazz.getMethods()) {
      if (method.getName().equals("...")) {
        ...
      }
    }
    

    The reason for this is that there can be multiple methods with the same name and different parameter types (ie the method name is overloaded).

    getMethods() returns all the public methods in the class, including those from superclasses. An alternative is Class.getDeclaredMethods(), which returns all methods in that class only.

    0 讨论(0)
  • 2020-12-10 19:17

    You can loop over all methods of a class using:

    cls.getMethods(); // gets all public methods (from the whole class hierarchy)
    

    or

    cls.getDeclaredMethods(); // get all methods declared by this class
    

    .

    for (Method method : cls.getMethods()) {
        // make your checks and calls here
    }
    
    0 讨论(0)
  • 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);
      }
    }
    
    0 讨论(0)
  • 2020-12-10 19:37

    You can use getMethods() which returns an array of all methods of a class. Inside the loop you can inspect the parameters of each method.

    for(Method m : cl.getMethods()) {
       Class<?>[] params = m.getParameterTypes();
       ...
    }
    

    Otherwise you can use getDelcaredMethods() which will allow you to "see" private methods (but not inherited methods). Note that if you want to invoke a private methods you must first apply setAccessible(boolean flag) on it:

    for(Method m : cl.getDelcaredMethods()) {
       m.setAccessible(true);
       Class<?>[] params = m.getParameterTypes();
       ...
    }
    
    0 讨论(0)
提交回复
热议问题