Intercepting by object type
Problem:
You have a factory in your code that creates various types of objects, and you want to apply different interceptors according to object type.
Solution 1
Create multiple interception stacks and then wrap up each
in an injector. Apply the appropriate injector based on the object that
you are creating - a map (from Class
to
InterceptionInjector
) may be useful.
For example:
public void init() { MethodInterceptorStack stackA = InterceptorStack.singleton(interceptorA); MethodInterceptorStack stackB = InterceptorStack.singleton(interceptorB); this.map = new HashMap<Class, InterceptionInjector>( ); this.map.put( FirstClass.class , new ProxyInjector(stackA) ); this.map.put( SecondClass.class , new ProxyInjector(stackB) ); this.map.put( ThirdClass.class , new ProxyInjector(stackB) ); } public <T> T intercept( T object ) { ProxyInjector injector = this.map.get( type.getClass() ); return injector.wrapObject( MyInterface.class, object ); }
Solution 2
Use the InstanceOfRule or the NotInstanceOfRule to match based on the type of the object being intercepted. The InterceptionBuilder can be used to apply these interceptors to your stack.
public void init() { InterceptionBuilder builder = new InterceptionBuilder(); builder.whenInstanceOf(FirstClass.class, interceptorA); builder.whenNotInstanceOf(FirstClass.class, interceptorB); this.injector = new ProxyInjector( builder.done() ); } public <T> T intercept( T object ) { return this.injector.wrapObject( MyInterface.class, object ); }