• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Can you add a method to an object?

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
After I have instaniated an object from a class, is it then possible to add methods to my object?
 
Ranch Hand
Posts: 326
Android Mac OS X Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I didn't think so and your explanation is very helpful...THANK YOU!
 
Bras cause cancer. And tiny ads:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic