aspose file tools*
The moose likes Beginning Java and the fly likes Can you add a method to an object? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can you add a method to an object?" Watch "Can you add a method to an object?" New topic
Author

Can you add a method to an object?

Paul Hoffman
Greenhorn

Joined: Nov 04, 2005
Posts: 19
After I have instaniated an object from a class, is it then possible to add methods to my object?
Ove Lindström
Ranch Hand

Joined: Mar 10, 2008
Posts: 326

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

Joined: Nov 04, 2005
Posts: 19
I didn't think so and your explanation is very helpful...THANK YOU!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can you add a method to an object?