So, I understand that the answer to this is probably βit's complicated,β but:
I have a strange idea, and I was wondering if it is possible to create a method in Java such as:
<T> T wrapInterface (Class<T> interfaceClass, T wrappedObject) { if (mClass.isInterface()) { //create a new implementation of interfaceClass that, in each method, //does some action before delegating to wrappedObject return thatImplementation; } }
Basically, if my Foo interface defined the foo () method, I would like this method to create a new class that looks something like this, instantiate this class with wrappedObject as a constructor parameter, and then return this:
public class GeneratedClass implements Foo { private Foo wrapped; public GeneratedClass (Foo wrapped) { this.wrapped = wrapped; } @Override public void foo () { System.out.println("Calling Foo.foo() on wrapped object " + wrapped.toString()); wrapped.foo(); } }
The application that I am considering is more complex than just writing to a log, but a log is enough for this idea. I would like to do this with a lot of interface types, so I would not just write all the GeneratedClasses manually.
Bonus points for a solution that does not require additional linguistic functions (bringing AspectJ or something like that) and double bonus points, if this is possible only using standard JDK libraries.
(I donβt need an exact compiled answer, just a pointer to the necessary toolboxes / libraries / etc that would allow me to do this.)
Thanks!
java interface code-generation wrapping
Sbodd
source share