[关闭]
@big-bear 2018-01-11T09:03:04.000000Z 字数 1053 阅读 791

java通过反射执行私有方法

Java


日常code的时候,当你需要处理复杂业务逻辑的时候,经常会为了是代码结构清楚将部分代码抽成一个私有方法,有时候需要单元测试一下私有方法.java的发射机制提供了给我们测试类的私有方法的途径.

  1. /**
  2. * 执行类的私有方法
  3. * @param obj 调用方法的对象
  4. * @param clazz 私有方法所在的类
  5. * @param methodName 私有方法名
  6. * @param classes 参数类型数组
  7. * @param objects 参数数组
  8. * @return 方法的返回值
  9. */
  10. public Object invoke(final Object obj,final Class clazz, final String methodName,
  11. final Class[] classes, final Object[] objects) {
  12. try {
  13. Method method = getMethod(clazz, methodName, classes);
  14. method.setAccessible(true);// 调用private方法的关键一句话
  15. return method.invoke(obj, objects);
  16. } catch (Exception e) {
  17. throw new RuntimeException(e);
  18. }
  19. }
  20. /**
  21. * 利用递归找一个类的指定方法,如果找不到,去父亲里面找直到最上层Object对象为止。
  22. *
  23. * @param clazz
  24. * 目标类
  25. * @param methodName
  26. * 方法名
  27. * @param classes
  28. * 方法参数类型数组
  29. * @return 方法对象
  30. * @throws Exception
  31. */
  32. private Method getMethod(Class clazz, String methodName,
  33. final Class[] classes) {
  34. Method method = null;
  35. try {
  36. method = clazz.getDeclaredMethod(methodName, classes);
  37. } catch (NoSuchMethodException e) {
  38. try {
  39. method = clazz.getMethod(methodName, classes);
  40. } catch (NoSuchMethodException ex) {
  41. if (clazz.getSuperclass() == null) {
  42. return method;
  43. } else {
  44. method = getMethod(clazz.getSuperclass(), methodName,
  45. classes);
  46. }
  47. }
  48. }
  49. return method;
  50. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注