Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a method is an override? [duplicate]

Possible Duplicate:
Detect if a method was overridden using Reflection (C#)

Is there a way to tell if a method is an override? For e.g.

public class Foo
{
    public virtual void DoSomething() {}
    public virtual int GimmeIntPleez() { return 0; }
}

public class BabyFoo: Foo
{
    public override int GimmeIntPleez() { return -1; }
}

Is it possible to reflect on BabyFoo and tell if GimmeIntPleez is an override?

like image 712
Water Cooler v2 Avatar asked Jun 16 '10 18:06

Water Cooler v2


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.

Can we override override method?

A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited, then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.

Which method does not get override?

Static methods can not be overridden We can not override the static methods in a derived class because static methods are linked with the class, not with the object. It means when we call a static method then JVM does not pass this reference to it as it does for all non-static methods.


2 Answers

You can use MethodInfo.DeclaringType to determine if the method is an override (assuming that it's also IsVirtual = true).

From the documentation:

...note that when B overrides virtual method M from A, it essentially redefines (or redeclares) this method. Therefore, B.M's MethodInfo reports the declaring type as B rather than A, even though A is where this method was originally declared...

Here's an example:

var someType = typeof(BabyFoo);
var mi = someType.GetMethod("GimmeIntPleez");
// assuming we know GimmeIntPleez is in a base class, it must be overriden
if( mi.IsVirtual && mi.DeclaringType == typeof(BabyFoo) )
    { ... }
like image 121
LBushkin Avatar answered Sep 20 '22 11:09

LBushkin


Test against MethodInfo.GetBaseDefinition(). If the function is an override, it will return a different method in a base class. If it's not, the same method object will be returned.

When overridden in a derived class, returns the MethodInfo object for the method on the direct or indirect base class in which the method represented by this instance was first declared.

like image 29
zildjohn01 Avatar answered Sep 22 '22 11:09

zildjohn01