1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mortbay.jetty.plus.annotation;
17
18 import java.lang.reflect.Method;
19 import java.lang.reflect.Modifier;
20
21 import org.mortbay.util.IntrospectionUtil;
22 import org.mortbay.util.Loader;
23
24
25
26
27
28
29
30
31 public abstract class LifeCycleCallback
32 {
33 public static final Object[] __EMPTY_ARGS = new Object[] {};
34 private Method _target;
35 private Class _targetClass;
36
37
38 public LifeCycleCallback()
39 {
40 }
41
42
43
44
45
46 public Class getTargetClass()
47 {
48 return _targetClass;
49 }
50
51
52
53
54
55 public void setTargetClass(Class clazz)
56 {
57 _targetClass = clazz;
58 }
59
60
61
62
63
64 public Method getTarget()
65 {
66 return _target;
67 }
68
69
70
71
72 public void setTarget(Method target)
73 {
74 this._target = target;
75 }
76
77
78
79
80 public void setTarget (Class clazz, String methodName)
81 {
82 try
83 {
84 Method method = IntrospectionUtil.findMethod(clazz, methodName, null, true, true);
85 validate(clazz, method);
86 _target = method;
87 _targetClass = clazz;
88 }
89 catch (NoSuchMethodException e)
90 {
91 throw new IllegalArgumentException ("Method "+methodName+" not found on class "+clazz.getName());
92 }
93 }
94
95
96
97
98 public void callback (Object instance)
99 throws Exception
100 {
101 if (getTarget() != null)
102 {
103 boolean accessibility = getTarget().isAccessible();
104 getTarget().setAccessible(true);
105 getTarget().invoke(instance, __EMPTY_ARGS);
106 getTarget().setAccessible(accessibility);
107 }
108 }
109
110
111
112
113
114
115
116
117
118
119
120
121
122 public Method findMethod (Package pack, Class clazz, String methodName, boolean checkInheritance)
123 {
124 if (clazz == null)
125 return null;
126
127 try
128 {
129 Method method = clazz.getDeclaredMethod(methodName, null);
130 if (checkInheritance)
131 {
132 int modifiers = method.getModifiers();
133 if (Modifier.isProtected(modifiers) || Modifier.isPublic(modifiers) || (!Modifier.isPrivate(modifiers)&&(pack.equals(clazz.getPackage()))))
134 return method;
135 else
136 return findMethod(clazz.getPackage(), clazz.getSuperclass(), methodName, true);
137 }
138 return method;
139 }
140 catch (NoSuchMethodException e)
141 {
142 return findMethod(clazz.getPackage(), clazz.getSuperclass(), methodName, true);
143 }
144 }
145
146 public boolean equals (Object o)
147 {
148 if (o==null)
149 return false;
150 if (!(o instanceof LifeCycleCallback))
151 return false;
152 LifeCycleCallback callback = (LifeCycleCallback)o;
153
154 if (callback.getTargetClass()==null)
155 {
156 if (getTargetClass() != null)
157 return false;
158 }
159 else if(!callback.getTargetClass().equals(getTargetClass()))
160 return false;
161 if (callback.getTarget()==null)
162 {
163 if (getTarget() != null)
164 return false;
165 }
166 else if (!callback.getTarget().equals(getTarget()))
167 return false;
168
169 return true;
170 }
171
172 public abstract void validate (Class clazz, Method m);
173 }