在学习java反射中我们常常会遇到下面三对双胞胎:
getDeclaredConstructors和getConstructors
getDeclaredMethods和getMethods
getDeclaredFields和getFields
看起来三者很类似,经常使用起来我们不知道该用谁
getDeclaredXX不包括父类的方法,专注于获取本类的所有方法(包括public和非public)
getXX包括派生链上所有父类和本类的所有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.(重点是这句,不包括继承的方法也就是父类中的方法)
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;
}
public native Method[] getDeclaredMethodsUnchecked(boolean publicOnly);
让我们看下getDeclaredMethodsUnchecked的注释
/**
* Populates a list of methods without performing any security or type
* resolution checks first. If no methods exist, the list is not modified.
*
* @param publicOnly Whether to return only public methods.
* @hide
*/
我们看到参数这里就是确定是否只返回public修饰的方法,getDeclaredMethods里面我们给的参数是false,所以返回的是所有修饰符的方法,属性,构造器和这个定义一样