In the third-party library that I use, the following bit of the hierarchy exists:
public abstract class Foo {
Various methods in the library work with things like Foo
. Foo
docs say that users can extend Foo
to make a specific implementation, and (obviously) the library provides a specific implementation.
I am pleased with the implementation of the library, except for one method whose behavior I would like to change a little. But the hierarchy that was provided to me disconnects me.
If Foo
was an interface (itβs not!), I would just do this:
public FooWrapper implements Foo { private Foo wrappedImpl; public FooWrapper(Foo toBeWrapped) { wrappedImpl = toBeWrapped; } List<Whatever> methodIWantToTweak() { List<Whatever> list = wrappedImpl.methodIWantToTweak(); do_something_to_list(list); return list; } Something methodThatsOk() { return wrappedImpl.methodThatsOk(); }
But since this is not an interface, I cannot do this, or at least I cannot do it as cleanly as possible.
The only thing I can come up with is:
1) Extend the FooImpl API non-public class and override the method I want to configure.
2) Do something like:
public class FooWrapper extends Foo { private Foo wrappedImpl; public FooWrapper(Foo toBeWrapped) { super(); wrappedImpl = toBeWrapped; } List<Whatever> methodIWantToTweak() { List<Whatever> list = wrappedImpl.methodIWantToTweak(); do_something_to_list(list); return list; } Something methodThatsOk() { return wrappedImpl.methodThatsOk(); }
Both of these approaches smell like hell. The first problem is that it depends on a class that it should not be aware of, and which may be changed / disappeared / renamed in future versions of the library. The second problem is that a piece of the FooWrapper
superclass is FooWrapper
actually used and that it is impossible to override any final or private Foo
methods (which will cause problems, since wrappedImpl
cannot be delegated in those cases).
I think I will have to go with the first approach, because at least it will give the correct behavior, while the second will most likely be broken in a potentially evil, subtle way depending on the internal details of Foo
.
Am I really out of luck? What other approaches / ideas am I missing?