获取要反射的方法
获取反射方法时,有两个方法,getMethod 和 getDeclaredMethod。
class Class { @CallerSensitive public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException { Objects.requireNonNull(name); SecurityManager sm = System.getSecurityManager(); if (sm != null) { // 1. 检查方法权限 checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true); } // 2. 获取方法 Method method = getMethod0(name, parameterTypes); if (method == null) { throw new NoSuchMethodException(methodToString(name, parameterTypes)); } // 3. 返回方法的拷贝 return getReflectionFactory().copyMethod(method); } @CallerSensitive public Method getDeclaredMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException { Objects.requireNonNull(name); SecurityManager sm = System.getSecurityManager(); if (sm != null) { // 1. 检查方法是权限 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true); } // 2. 获取方法 Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes); if (method == null) { throw new NoSuchMethodException(methodToString(name, parameterTypes)); } // 3. 返回方法的拷贝 return getReflectionFactory().copyMethod(method); } }
以上是Java中如何使用反射获取指定方法?的详细内容。更多信息请关注PHP中文网其他相关文章!