Overriding a method in an instantiated Java object
You can't really change an object on the fly in java.
You could have something which do what you want by wrapping your Foo
into another similar objet which will delegate every call to Foo
and at the same log everything you want. (see Proxy
)
But if you want to do logging, maybe aspect is a better choice. (see AspectJ)
You can't replace methods in existing objects - you can't change an existing object's type, for one thing.
You could create a new instance of another class which delegated to the existing instance, but that has limitations too.
In your real world case is there no way you can simply make a separate call to wrap the streams returned by the socket? Can you give more details.
Since Java uses class-based OO, this is impossible. What you can do is use the decorator pattern, i.e. write a wrapper for the object that returns the wrapped streams.
I think there is a way to achieve the effect you want. I saw it orriginally used in swing with buttons to allow the programmer to make the button do something when it is clicked.
Say you have your Foo class:
public class Foo {
public Bar doBar() {
// Some activity
}
}
Then you have a runner class or something similar. You can override the doBar() method at the point of instantiation and it will only affect that specific object.
that class may look like this:
public class FooInstance{
Foo F1 = new Foo(){
public Bar doBar(){
//new activity
}
}
Foo F2 = new Foo();
F1.doBar(); //does the new activity
F2.doBar(); //does the original activity found in the class
}
I'm not entirely sure that will do the trick for you but maybe it'll set you in the right direction. If nothing else it is possible to override a method outside of the class, maybe that will help you.