Java反射 getMethods() 和 getDeclaredMethods()

132 阅读1分钟

getMethods()

/**
 * Returns an array containing {@code Method} objects reflecting all the
 * public methods of the class or interface represented by this {@code
 * Class} object, including those declared by the class or interface and
 * those inherited from superclasses and superinterfaces.
 ...
 * @since JDK1.1
 */
@CallerSensitive
public Method[] getMethods() throws SecurityException {
    List<Method> methods = new ArrayList<Method>();
    getPublicMethodsInternal(methods);
    /*
     * Remove duplicate methods defined by superclasses and
     * interfaces, preferring to keep methods declared by derived
     * types.
     */
    CollectionUtils.removeDuplicates(methods, Method.ORDER_BY_SIGNATURE);
    return methods.toArray(new Method[methods.size()]);
}

getMethods() 官方注释写的是,返回所有 public 方法,包括 那些 由类或接口声明的 和 那些继承自超类和超接口的。

这个文档是写的有些歧义的,包括 也就是说,返回的方法都是 public 方法,并且继承的实现的方法也必须都是 public

严谨一点就是:也就是说他会返回该类继承的和自己声明,所有的 public 方法

getDeclaredMethods()

/**
 * Returns an array containing {@code Method} objects reflecting all the
 * declared methods of the class or interface represented by this {@code
 * Class} object, including public, protected, default (package)
 * access, and private methods, but excluding inherited methods.
 ...
 * @since JDK1.1
 */
public Method[] getDeclaredMethods() throws SecurityException {
    Method[] result = getDeclaredMethodsUnchecked(false);
    for (Method m : result) {
        // Throw NoClassDefFoundError if types cannot be resolved.
        m.getReturnType();
        m.getParameterTypes();
    }
    return result;
}

getDeclaredMethods()返回所有 声明的方法 ,包括public、protected、default(package)访问和私有方法,但不包括继承方法。

这个也是有歧义的,不包括继承方法???
那么我重写了一个方法,这算不算继承方法呢?
事实证明是算的,重写了之后,就算是 声明的方法了

所以严谨一点应该是:返回当前声明在当前类内的所有方法

总结

  1. getMethods() 只能拿到 public方法,并且是该类继承的和自己声明所有的 public 方法
  2. getgetDeclaredMethods() 可以跨过 访问权限,但是只能拿到 类内声明的方法

ps:反射可以获取的方法包括 Native方法,但是无法获得运行时变量,比如局部变量