Consider Java code that is based on the rather common pattern of factories, producing instances of some interface you want to use. In the simple case this works fine but what do you do when you want to modify a method in the returned instance? If there where no factory involved you could just inherit from the class anonymously and override that method. But given that the object is created via a factory that option is closed to us.

Luckily there is a solution for us in the Java API, the java.lang.reflect.Proxy classes newProxyInstance method. This however have a rather clunky interface where we are expected to handle Method objects and InvocationHandler instances.

We can do better than that.

After a bit of experimenting I came up with the following API

public class Decorator { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public static @interface Override {} public static <I, T extends I,D> I decorate(T proxyBase, Class<I> asInterface, D decorations) throws NoSuchMethodException { // ... Implementation } }

Which is used like this

MyInterface m=Decorator.decorate(MyInterfaceFactory.create(), MyInterface.class, new Object(){ @Decorator.Override void close(MyInterface i){ System.err.println("Closing down"); i.close(); } }); m.close(); // Will print "Closing down"

source code: Decorator.java
test case: Test.java

Enjoy

Feel free to use this code for any and all purposes, consider it in the public domain or if that is not workable for you you can use it under the terms of the MIT License