Automatic delegation in Java

I would like to add some functions to the object that will be created at runtime. However, the interface for this object is very large (and not under my control). I would like to wrap an object in my class that adds the functionality I want and delegates the standard interface functionality to the original object - is there a way to do this in Java without creating a 1-line copy-paste delegation method for each 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 ... } 

Which would I prefer:

 class MyFoo implements Foo { Foo wrapped; void myMethod() { ... } // automatically delegate undefined methods to wrapped object } 
+6
source share
1 answer

It looks like you need a dynamic proxy and intercept only the methods you want to override.

A dynamic proxy class is a class that implements a list of interfaces specified at runtime, so a method call through one of the interfaces on the class instance will be encoded and sent to another object through a single interface. Thus, a dynamic proxy class can be used to create a protected type of proxy object for a list of interfaces that do not require a preliminary generation of a proxy class, such as with compile-time tools. A method call to an instance of a dynamic proxy class is sent one method at a time to an instance invocation handler, and they are encoded using java.lang.reflect.Method, identifying the method that was invoked and an array of type Object containing arguments

(my emphasis)

By implementing InvocationHandler , you simply create one method that receives every call on this object (effectively what you described above is effective)

+10
source

All Articles