littlerunaway
littlerunaway

Reputation: 453

I need to check if a method is overridden

this is about a hw assignment that includes reflection in Java. suppose I have 2 classe :

public class A{
   bool foo(){...}
}

public class B extends A{
   bool foo(){...}
}

suppose I have a function that receives Class<?> parameter, and I want to check if foo is overridden in some derived class, without knowing if there are any, how do I do that?

I read a few questing regarding the same subject, that mentioned isBridge, or getDeclaringclass but can't figure out what those do.

I have to mention that I don't know Java all that well. this is part of an Object Oriented Programming class I'm taking, so it's not meant to make us experts in Java but to demonstrate the principals. which means the solution to my problem shouldn't be too complex.

Upvotes: 3

Views: 1734

Answers (1)

Daniel Rodriguez
Daniel Rodriguez

Reputation: 176

Given:

class A 
    {
        public void foo()
        {
            System.out.println("Ok on A");
        }
    }
    class B extends A
    {
        public void foo()           
        {
            System.out.println("Ok on B");
        }
    }

You could traverse the hierarchy tree of classes searching for the method

String methodName="foo";
Class currentClass=B.class.getSuperclass();
boolean overwritten=false;
while(currentClass!=Object.class && !overwritten)
{
    try
    {
        Method m=currentClass.getMethod(methodName);
        overwritten=true;
        break;
    }
    catch (NoSuchMethodException e) {
        // Method does not exists
    } catch (SecurityException e) {
        // Security exception
    }
    currentClass=currentClass.getSuperclass();
}

if overwritten is true, we found the method in some parent class.

Notice we are checking a method without parameters (foo), to find a method with parameters, you have to specify them as second parameter in getMethod call.

Now, if you want to find if "any class" has overriden the foo method, you will have to scan all classes in your classpath, search if they contains the target method, and do the same test for each one, or use a reflection library like org.reflections , you can find more information on subclass finding in the following post: how-do-you-find-all-subclasses-of-a-given-class-in-java

Upvotes: 1

Related Questions