Are there equivalents to Ruby's method_missing in other languages?

前端 未结 15 1626
渐次进展
渐次进展 2020-12-08 08:00

In Ruby, objects have a handy method called method_missing which allows one to handle method calls for methods that have not even been (explicitly) defined:

相关标签:
15条回答
  • 2020-12-08 08:57

    Boo has IQuackFu - there is already an excellent summary on SO at how-can-i-intercept-a-method-call-in-boo

    Here is an example:

    class XmlObject(IQuackFu):
    _element as XmlElement 
    
    def constructor(element as XmlElement):
        _element = element 
    
    def QuackInvoke(name as string, args as (object)) as object:
        pass # ignored 
    
    def QuackSet(name as string, parameters as (object), value) as object:
        pass # ignored 
    
    def QuackGet(name as string, parameters as (object)) as object:
        elements = _element.SelectNodes(name)
        if elements is not null:
            return XmlObject(elements[0]) if elements.Count == 1
            return XmlObject(e) for e as XmlElement in elements 
    
    override def ToString():
        return _element.InnerText 
    
    0 讨论(0)
  • 2020-12-08 08:58

    In Common Lisp, no-applicable-method may be used for this purpose, according to the Common Lisp Hyper Spec:

    The generic function no-applicable-method is called when a generic function is invoked and no method on that generic function is applicable. The default method signals an error.

    The generic function no-applicable-method is not intended to be called by programmers. Programmers may write methods for it.

    So for example:

    (defmethod no-applicable-method (gf &rest args)
      ;(error "No applicable method for args:~% ~s~% to ~s" args gf)
      (%error (make-condition 'no-applicable-method :generic-function gf :arguments args) '()
            ;; Go past the anonymous frame to the frame for the caller of the generic function
            (parent-frame (%get-frame-ptr))))
    
    0 讨论(0)
  • 2020-12-08 09:00

    In CFML (ColdFusion, Railo, OpenBD), the onMissingMethod() event handler, defined within a component, will receive undefined method calls on that component. The arguments missingMethodName and missingMethodArguments are automatically passed in, allowing dynamic handling of the missing method call. This is the mechanism that facilitated the creation of implicit setter/getter schemes before they began to be built into the various CFML engines.

    0 讨论(0)
提交回复
热议问题