Java反射 : Declared的作用 ( 例如 : getMethods和getDeclaredMethods )
2018-02-28 16:38
567 查看
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)方法,但是并不包括继承自父类或父接口的方法。
相关文章推荐
- java反射中getDeclaredMethods和getMethods的区别
- java反射中getDeclaredMethods和getMethods的区别
- 试用Java中的反射reflect之getDeclaredMethods和getMethods
- Java反射getMethods()与getDeclaredMethods()区别
- Java,反射的用法,getDeclaredMethods与getMethods 的区别
- java反射中getDeclaredMethods和getMethods的区别
- Java中的反射reflect之getDeclaredMethods和getMethods
- java 反射机制 之 getMethods获取所有公有方法 和 getDeclaredMethods 获取本类所有方法
- Java 反射(Reflection) - Class 类 getMethod、getMethods、getDeclaredMethod、getDeclaredMethods四者区别
- 反射中getMethods 与 getDeclaredMethods 的区别
- java中Class.getMethods()和Class.getDeclaredMethods()方法的区别
- java反射之Class.getMethod与getDeclaredMethods()区别
- 反射以及 getDeclaredMethods()和getMethods()区别
- 反射中getMethods 与 getDeclaredMethods 的区别
- 反射中getMethods 与 getDeclaredMethods 的区别
- 反射中getMethods 与 getDeclaredMethods 的区别
- [JAVA]反射机制按顺序获取getDeclaredFields()/getDeclaredMethods()
- 反射中getMethods 与 getDeclaredMethods 的区别
- 反射中getMethods 与 getDeclaredMethods 的区别
- Java反射 getFields()和getDeclaredFields()的区别