I would like to add some functionality to an object that will be generated at runtime. However, the interface for this object is very large (and not under my control). I would like to wrap the object in my own class which adds the functionality I want and delegates the standard interface functionality to the original object - is there any way to do this in Java without creating a 1-line copy-paste delegator method for every method in the interface?
What I want to avoid:
class MyFoo implements Foo {
Foo wrapped;
void myMethod() { ... }
void interfaceMethod1() wrapped.interfaceMethod1();
int interfaceMethod2() wrapped.interfaceMethod2();
// etc etc ...
}
What I would prefer:
class MyFoo implements Foo {
Foo wrapped;
void myMethod() { ... }
// automatically delegate undefined methods to wrapped object
}
Delegation is simply passing a duty off to someone/something else. Delegation can be an alternative to inheritance. Delegation means that you use an object of another class as an instance variable, and forward messages to the instance.
Delegation is an alternative to inheritance for reusing code among multiple classes. Inheritance uses the IS-A relationship for re-use; delegation uses the HAS-A reference relationship to do the same. Inheritance and delegation have the same kind of relationship that, say, Aspirin and Tylenol, have.
In object-oriented programming, delegation refers to evaluating a member (property or method) of one object (the receiver) in the context of another original object (the sender).
The Delegation Model is available in Java since Java 1.1.
Sounds like you need a dynamic proxy and intercept merely the methods you want to override.
A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools. Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments
(my emphasis)
By implementing InvocationHandler you simply create one method that receives every invocation on that object (effectively what you've described above)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With