How can I add methods to a class at runtime in Smalltalk?

后端 未结 4 468
长情又很酷
长情又很酷 2020-12-29 14:44

I\'m building a Smalltalk API to an XML-based web service. The XML service is so regular that, rather than write the methods by hand, I figured I\'d just override #doe

4条回答
  •  無奈伤痛
    2020-12-29 15:27

    Suppose you have template method:

    SomeClass>>himaker: aName
      Transcript show: 'Hi ...'
    

    Then you can copy it to other class, just don't forget to set selector and class if you don't want to confuse the system browser. Or if you don't care, that just install the copy at method dictionary.

    | method |
    
    method := (SomeClass>>#himaker:) copy.
    
    method methodClass: OtherClass.
    method selector: #boo: .
    OtherClass methodDict at: #boo: put: method.
    
    method := method copy.
    method selector: #bar: .
    method methodClass: OtherClass2.
    OtherClass2 methodDict at: #bar: put: method.
    

提交回复
热议问题