Java反射中getMethods()与getDeclaredMethod()区别

柔光的暖阳◎ 2021-06-22 15:38 476阅读 0赞

getMethods

获取当前类和父类的所有公有方法(私有的不返回),数组形式返回

  1. @CallerSensitive
  2. public Method[] getMethods() throws SecurityException {
  3. checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
  4. return copyMethods(privateGetPublicMethods());
  5. }

getDeclaredMethods

只查询当前类的所有定义的方法(包含私有的),同时还有重载方法,直接根据name和参数类型返回一个方法。找不到方法抛出NoSuchMethodException

  1. @CallerSensitive
  2. public Method[] getDeclaredMethods() throws SecurityException {
  3. checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
  4. return copyMethods(privateGetDeclaredMethods(false));
  5. }
  6. @CallerSensitive
  7. public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
  8. throws NoSuchMethodException, SecurityException {
  9. checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
  10. Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
  11. if (method == null) {
  12. throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
  13. }
  14. return method;
  15. }

发表评论

表情:
评论列表 (有 0 条评论,476人围观)

还没有评论,来说两句吧...

相关阅读