Java反射 : Declared的作用 ( 例如 : getMethods和getDeclaredMethods )

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)方法,但是并不包括继承自父类或父接口的方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值