Tyler Szabo Tyler Szabo - 1 month ago 5
Java Question

Overriding a method in an instantiated Java object

I would like to override a method in an object that's handed to me by a factory that I have little control over.

My specific problem is that I want to override the getInputStream and getOutputStream of a Socket object to perform wire logging.

However the generic problem is as follows:

public class Foo {
public Bar doBar() {
// Some activity
}
}


Where I'd like to take an instantiated
Foo
and replace the
doBar
with my own that would work as follows:

Bar doBar() {
// My own activity
return original.doBar();
}


For the Socket I'm going to return an InputStream and OutputStream that are wrapped by logging to intercept the data.

Answer

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.

Comments