Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to find if a method is overridden from base class? [duplicate]

How to find out if a method is overridden by child classes?

For example,

public class Test {

static public class B {
    public String m() {return "From B";};
}

static public class B1 extends B {

}

static public class B2 extends B {
    public String m() {return "from B2";};
}

/**
 * @param args
 * @throws FileNotFoundException 
 */
public static void main(String[] args)  {

    B b1 = new B1();
    System.out.println("b1 = " + b1.m());
    B b2 = new B2();
    System.out.println("b1 = " + b2.m());
}

}

Given an instance of B, how do I know if any derived classes have overridden method m() like B2?

Update: My question wasn't clear. Actually, I was trying to ask if this is possible without resorting to reflection. This check is done in a tight loop and it's used in a performance hack to save a few CPU cycles.

like image 845
ZZ Coder Avatar asked Jan 27 '11 20:01

ZZ Coder


People also ask

How do we identify if a method is an overridden method?

getMethod("myMethod"). getDeclaringClass(); If the class that's returned is your own, then it's not overridden; if it's something else, that subclass has overridden it.

How do you find the overridden method of base class?

Calling Parent class's overridden method from Child class's method using super keyword. from Derived class function will call base class version of display() function i.e.

Can method be overriden in the same class?

Therefore, you cannot override two methods that exist in the same class, you can just overload them.

Are overridden methods inherited?

Overridden methods are not inherited.


1 Answers

This question helps demonstrate how to get the information of which class that method belongs to:

How to quickly determine if a method is overridden in Java

class.getMethod("myMethod").getDeclaringClass();
like image 183
Lithium Avatar answered Oct 06 '22 11:10

Lithium