1. package com.pigetest.util;
  2. import java.lang.reflect.Method;
  3.  
  4. public class PrivateMethodTestHelper {
  5. public static Object invoke(String clazzName,String methodName,Object...params){
  6. try {
  7. Class<?> clazz=Class.forName(clazzName);
  8. Object obj=clazz.newInstance();
  9. Method[] methods = clazz.getDeclaredMethods();
  10. Method callMethod=null;
  11. for(Method method:methods){
  12. if(method.getName().equals(methodName)){
  13. callMethod=method;
  14. break;
  15. }
  16. }
  17. callMethod.setAccessible(true);
  18. return (Object) callMethod.invoke(obj,params);
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. }
  22. return null;
  23. }
  24. public static void main(String[] args) {
  25. int value=(Integer) PrivateMethodTestHelper.invoke("com.pigetest.util.AddNumber","addNumber",1,2);
  26. System.out.println(value);
  27. }
  28. }

 

版权声明:本文为programerlrc原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/programerlrc/p/5628128.html