Using Java reflection to create eval() method

后端 未结 4 555
-上瘾入骨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.

提交回复
热议问题