views:

200

answers:

1

I am trying to use Spring framework to dynamically implement a specific interface (lets call it I) for a class (let call it C). In Spring this is called introduction (mixin in other languages). In compile time C doesn't implement I. Using the @DeclareParents annotation I can do it in AspectJ syntax.

The problem is that the actual implementation of I (lets call it IImpl) is standalone (not dependent on the context) - I should only supply the IImpl class name in the annotation. What I want to achieve is the implementation that is stipulated in some way. For example, I would like to provide the IImpl instance with a parameter, say the enclosing C instance, so that the logic in IImpl would be different depending on what instance of C I am introducing. I need some way to set the dependecy between the IImpl instance and the introduced C instance.

Currently I cannot find a way to do it. Any ideas?

Thanks.

+2  A: 

I'm afraid the 'form' of the solution you are looking for is not possible as the AJ bytecode weaver (doesn't matter if compile or load time) needs to know how to 'implement' your methods. But, I think there might be a solution for your question in the form of a delegator. Basically, you'll tell C to implement interface I using IImpl and use IImpl as a delegator, meaning that IImpl will delegate all method calls to an IRuntimeImpl that can be configured/changed in at runtime. IImpl will basically be:

public class IImpl implements I {
    private I delegate;

    public void interfaceMethod() {
        delegate.interfaceMethod()
    }
}

At runtime you'll be able to pass to IImpl whatever runtime implementation you pick for I.

./alex

alexpopescu
But that's exactly the problem - how do I pass anything to IImpl? Using @DeclareParents I can only supply the class name of IImpl, and I don't see a way to pass its instance any parameters.
Stas
@Stas: I haven't used this functionality, but here's what I expect. An instance of IImpl is built/instantiated by the engine. Now, you can instruct Spring to perform its magic by looking at the class annotations and I think there might be a way to tell Spring to initialize IImpl using the appcontext
alexpopescu