-1

Given the following code:

class A{
    int i;
        int hashcode(){
            . . .
        }
}

Precisely, given an object a of A how can one say that hashcode() which inherited from Object class is overridden in the class A.

a.getClass().getDeclaringClass() is returning Objectclass. I want it to output A.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
sri91
  • 182
  • 9
  • http://stackoverflow.com/a/2315467/584862 – mre Dec 09 '13 at 14:17
  • @sᴜʀᴇsʜᴀᴛᴛᴀ Note that we are not looking for overridden methods, but for overriding methods. Both have not the same solution. – sp00m Dec 10 '13 at 08:15

2 Answers2

1

This should suit your needs:

public static Set<Method> findOverridingMethods(Object o) {
    Set<Method> overridingMethods = new HashSet<Method>();
    Class<?> clazz = o.getClass();
    for (Method method : clazz.getDeclaredMethods()) {
        Class<?> current = clazz.getSuperclass();
        while (current != null) {
            try {
                current.getDeclaredMethod(method.getName(), method.getParameterTypes());
                overridingMethods.add(method);
            } catch (NoSuchMethodException ignore) {
            }
            current = current.getSuperclass();
        }
    }
    return overridingMethods;
}
sp00m
  • 47,968
  • 31
  • 142
  • 252
0

I think that you have to use the Method object obtained by using

getClass().getDeclaredMethod("hashCode").getDeclaringClass()
Adam Arold
  • 29,285
  • 22
  • 112
  • 207