/** * Finds public non-static method that is accessible from public class. * * @param type the class that can have method * @param name the name of method to find * @param args parameter types that is used to find method * @return object that represents found method * @throws NoSuchMethodException if method could not be found or some methods are found */ public static Method findInstanceMethod(Class<?> type, String name, Class<?>... args) throws NoSuchMethodException { Method method = findMethod(type, name, args); if (Modifier.isStatic(method.getModifiers())) { throw new NoSuchMethodException("Method '" + name + "' is static"); } return method; }
/** * Finds method that is accessible from public class or interface through class hierarchy. * * @param method object that represents found method * @return object that represents accessible method * @throws NoSuchMethodException if method is not accessible or is not found in specified * superclass or interface */ public static Method findAccessibleMethod(Method method) throws NoSuchMethodException { Class<?> type = method.getDeclaringClass(); if (Modifier.isPublic(type.getModifiers()) && isPackageAccessible(type)) { return method; } if (Modifier.isStatic(method.getModifiers())) { throw new NoSuchMethodException("Method '" + method.getName() + "' is not accessible"); } for (Type generic : type.getGenericInterfaces()) { try { return findAccessibleMethod(method, generic); } catch (NoSuchMethodException exception) { // try to find in superclass or another interface } } return findAccessibleMethod(method, type.getGenericSuperclass()); }