Adding/Overriding/Edit Body Methods to Class (Smalltalk - Squeak)
How can I ad开发者_StackOverflowd new methods or remove methods of a specific Class? Or, if I try to add a method which already exists so it will override it (although at this case I can just remove the old one and add the new one which is the same)?
Can it be done when the method itself is represented as a String? (I mean doing it without using external files and such but just have the method written as string).
For example a method that gets a class, a symbol and a string that is the code of the method and adds this method to aClass and if exists so override the old one:
in: aClass add: aSymbol sourceCode: aString
and usage example:
in: ClassA add: #something sourceCode: 'self subclassResponsibility'
It is quite easy. Check the category 'compiling' in Behavior class. You can do things like:
MyClass compile: 'something
^ self subclassResponsability'.
Check the rest of the methods in the 'compiling' category where you can specify in which category to put the method, to whom to notify, an error block, etc. If you call #compile: with a method that exist, it will just overwrite it.
For removing, the same, check methods like #removeSelector: implemented in Behavior or ClassDescription. You can do:
MyClass removeSelector: something.
Cheers
精彩评论