Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can you add a method to an object?

 
Paul Hoffman
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After I have instaniated an object from a class, is it then possible to add methods to my object?
 
Ove Lindström
Ranch Hand
Posts: 326
Android Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, not really... Not in the meaning as if you have this empty class



and then do



you could then do:




The true answer is "You don't want to do that!".

It IS possible to do it by manipulating on the byte code with some really fancy tricks. However... you don't want to do that. In most cases it is better to use Aspect Oriented Programing and put in cutpoints where you need to manipulate the code. Or use a Visitor pattern or Strategy pattern. Or even use the horrible ProxyClass (see See http://www.exampledepot.com/egs/java.lang.reflect/ProxyClass.html) if you are needing a custom implementation of an interface, and you only know the details at runtime.

Most of the time, it is better to change the model and use some sort of dependency injection of a custom class into another than trying to manipulate on the actual object. As stated in THGTTG, it is better to remove the mountain than trying to make it invisible...
 
Paul Hoffman
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didn't think so and your explanation is very helpful...THANK YOU!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic