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?
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.
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.
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.
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) )
{ ... }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With