1.方法示例
Java反射相关类中存在大量Declared方法,例如:
Class userClass = User.class;
Method[] methods1 = userClass.getMethods();
Method[] methods2 = userClass.getDeclaredMethods();
Method getUsrMethod = userClass.getDeclaredMethod("getUsername");
Annotation[] annotation1 = getUsrMethod.getAnnotations();
Annotation[] annotation2 = getUsrMethod.getDeclaredAnnotations();
getXxxxx以及getDeclaredXxxx方法到底有什么区别呢?
2.源码解读
先看一下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.
*
* ...省略
*
* @jls 8.2 Class Members
* @jls 8.4 Method Declarations
* @since JDK1.1
*/
@CallerSensitive
public Method[] getMethods() throws SecurityException {
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
return copyMethods(privateGetPublicMethods());
}
从方法注释可知:getMethods()返回的是当前Class对象的所有公有的方法,包含从父类或父接口继承而来的方法。
在看一下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.
*
* ...省略
*
* @jls 8.2 Class Members
* @jls 8.4 Method Declarations
* @since JDK1.1
*/
@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException {
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
return copyMethods(privateGetDeclaredMethods(false));
}
从方法注释可知:getDeclaredMethods()返回的是当前Class对象的所有(包括:public,protected,default,private)方法,但是并不包括继承自父类或父接口的方法。