/** * Returns overridden method from superclass if it exists. If method was not found returns null. * * @param method is method to find * @return overridden method from superclass */ public static Method getOverriddenMethod(Method method) { Class<?> declaringClass = method.getDeclaringClass(); Class<?> superClass = declaringClass.getSuperclass(); Method result = null; if (superClass != null && !(superClass.equals(Object.class))) { result = findMethod(method, superClass); } if (result == null) { for (Class<?> anInterface : declaringClass.getInterfaces()) { result = findMethod(method, anInterface); if (result != null) { return result; } } } return result; }
@Test public void testFindMethodForNullClass() throws Exception { Method method = ReflectionUtilsTest.class.getMethod("testFindMethodForNullClass", (Class<?>[]) null); assertNull(ReflectionUtils.findMethod(method, null)); }
@Test public void findMethodTest() throws NoSuchMethodException { final Method methodToFind1 = Child.class.getMethod("parametrizedMethod1", Integer.class); final Method method1 = ReflectionUtils.findMethod(methodToFind1, Parent.class); Assert.assertNotNull(method1); Assert.assertEquals(method1.getParameterTypes()[0], Number.class); final Method methodToFind2 = Child.class.getMethod("parametrizedMethod4", Long.class); final Method method2 = ReflectionUtils.findMethod(methodToFind2, Parent.class); Assert.assertNull(method2); }
/** * Returns overridden method from superclass if it exists. If method was not found returns null. * * @param method is method to find * @return overridden method from superclass */ public static Method getOverriddenMethod(Method method) { Class<?> declaringClass = method.getDeclaringClass(); Class<?> superClass = declaringClass.getSuperclass(); Method result = null; if (superClass != null && !(superClass.equals(Object.class))) { result = findMethod(method, superClass); } if (result == null) { for (Class<?> anInterface : declaringClass.getInterfaces()) { result = findMethod(method, anInterface); if (result != null) { return result; } } } return result; }