Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting that a method was not overridden

Say, I have the following 2 classes:

class A
  def a_method
  end
end

class B < A
end

Is it possible to detect from within (an instance of) class B that method a_method is only defined in the superclass, thus not being overridden in B?

Update: the solution

While I have marked the answer of Chuck as "accepted", later Paolo Perrota made me realize that the solution can apparently be simpler, and it will probably work with earlier versions of Ruby, too.

Detecting if "a_method" is overridden in B:

B.instance_methods(false).include?("a_method")

And for class methods we use singleton_methods similarly:

B.singleton_methods(false).include?("a_class_method")
like image 901
mxgrn Avatar asked Nov 08 '09 19:11

mxgrn


People also ask

How do you identify whether the method is overridden or not?

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.

Which method is not overridden?

Static methods can not be overridden 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. Therefore run-time binding cannot take place for static methods.

What does @override do in java?

The @Override annotation is one of a default Java annotation and it can be introduced in Java 1.5 Version. The @Override annotation indicates that the child class method is over-writing its base class method. It extracts a warning from the compiler if the annotated method doesn't actually override anything.

How do you force a method to be overridden?

Just make the method abstract. This will force all subclasses to implement it, even if it is implemented in a super class of the abstract class. Save this answer.


2 Answers

If you're using Ruby 1.8.7 or above, it's easy with Method#owner/UnboundMethod#owner.

class Module
  def implements_instance_method(method_name)
    instance_method(method_name).owner == self
    rescue NameError
    false
  end
end
like image 82
Chuck Avatar answered Oct 03 '22 00:10

Chuck


class A
  def m1; end
  def m2; end
end

class B < A
  def m1; end
  def m3; end
end

obj = B.new
methods_in_class = obj.class.instance_methods(false)  # => ["m1", "m3"]
methods_in_superclass = obj.class.superclass.instance_methods(false)  # => ["m2", "m1"]
methods_in_superclass - methods_in_class  # => ["m2"]
like image 29
Paolo Perrotta Avatar answered Oct 02 '22 22:10

Paolo Perrotta