Using Java reflection to create eval() method

后端 未结 4 530
-上瘾入骨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: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();
       ...
    }
    

提交回复
热议问题