1

How can I add 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'
user550413
  • 4,609
  • 4
  • 25
  • 26

1 Answers1

6

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

  • Thank you, I've read the description of #compile: but I couldn't actually understand what it returns? It just says that "Compile the argument, code, as source code in the context of the receiver". If I assume it creates a method code as expected I still couldn't find any useful method that could help me add this method to aClass. Any ideas? Maybe #compile: returns a CompiledMethod? It's not clear.. – user550413 May 01 '11 at 18:51
  • It is direclty added. When you do aClass compile: 'something self name. self doSomething', it compiles such method, it generates a CompiledMethod and it put it in the methodDict or aClass. So you can do: aClass methodDict at:#something and you will get the method, – Mariano Martinez Peck May 01 '11 at 19:33