KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tirsen > nanning > locking > SimpleMixinAspect


1 package com.tirsen.nanning.locking;
2
3 import com.tirsen.nanning.config.Aspect;
4 import com.tirsen.nanning.AspectInstance;
5 import com.tirsen.nanning.MixinInstance;
6 import com.tirsen.nanning.AspectException;
7
8 import java.util.Arrays JavaDoc;
9
10 /**
11  * Abstract utility base-classes for aspects that themselves add state and behaviour to objects. The
12  * aspect itself will be cloned and introduced as the target of a mixin. It can also add interceptors that work on
13  * the state and behavior introduced.
14  */

15 public abstract class SimpleMixinAspect implements Aspect, Cloneable JavaDoc {
16     private Class JavaDoc interfaceClass;
17
18     /**
19      * Subclasses using this constructor should implement one and only one interface, this interface will
20      * be used as the interface for the mixin.
21      */

22     public SimpleMixinAspect() {
23         setInterfaceClass(determineInterfaceClass(this.getClass()));
24     }
25
26     private Class JavaDoc determineInterfaceClass(Class JavaDoc targetClass) {
27         Class JavaDoc[] interfaces = targetClass.getInterfaces();
28         while (targetClass.getInterfaces().length == 0) {
29             targetClass = targetClass.getSuperclass();
30             interfaces = targetClass.getInterfaces();
31         }
32         assert targetClass != SimpleMixinAspect.class && interfaces.length == 1 :
33                 "your aspects class " + targetClass + " does not implement exactly one interface " + Arrays.asList(interfaces) +
34                 " you have to specify the mixins interface manually using setInterfaceClass(Class)";
35         Class JavaDoc interfaceClass = interfaces[0];
36         return interfaceClass;
37     }
38
39     public SimpleMixinAspect(Class JavaDoc interfaceClass) {
40         setInterfaceClass(interfaceClass);
41     }
42
43     protected void setInterfaceClass(Class JavaDoc interfaceClass) {
44         this.interfaceClass = interfaceClass;
45     }
46
47     public void introduce(AspectInstance instance) {
48         try {
49             instance.addMixin(new MixinInstance(interfaceClass, clone()));
50         } catch (Exception JavaDoc e) {
51             throw new AspectException(e);
52         }
53     }
54
55     public void advise(AspectInstance aspectInstance) {
56         Object JavaDoc target = aspectInstance.getMixinForInterface(interfaceClass).getTarget();
57         if (target == this) {
58             doAdvise(aspectInstance);
59
60         } else {
61             ((Aspect) target).advise(aspectInstance);
62         }
63     }
64
65     protected abstract void doAdvise(AspectInstance aspectInstance);
66 }
67
Popular Tags