Tyler Szabo Tyler Szabo - 1 year ago 81
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
and replace the
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download