01: package org.mockejb.interceptor;
02:
03: import java.lang.reflect.Method;
04:
05: /**
06: * Tests if the given class matches the class
07: * provided to the constructor of ClassPointcut.
08: *
09: * @author Alexander Ananiev
10: */
11: public class ClassPointcut implements Pointcut {
12:
13: private Class clazz;
14: private boolean matchSubclasses = false;
15:
16: /**
17: * Creates a new instance of ClassPoincut
18: * It will not match subclasses.
19: *
20: * @param clazz class to match
21: *
22: */
23: public ClassPointcut(final Class clazz) {
24: this .clazz = clazz;
25: }
26:
27: /**
28: * Creates a new instance of ClassPoincut
29: * @param clazz class to match
30: * @param matchSubclasses if true, the pointcut will also match all subclasses/
31: * subinterfaces of the provided class.
32: */
33: public ClassPointcut(final Class clazz,
34: final boolean matchSubclasses) {
35: this .clazz = clazz;
36: this .matchSubclasses = matchSubclasses;
37: }
38:
39: /**
40: * Tests if the class of the provided method is the same with the
41: * the class provided to the constructor of this pointcut.
42: * Note that it uses class equality, not instanceof.
43: *
44: * @return true if the provided method should be intercepted
45: */
46: public boolean matchesJointpoint(Method method) {
47:
48: boolean matches = false;
49: if (matchSubclasses) {
50: matches = clazz
51: .isAssignableFrom(method.getDeclaringClass());
52: } else {
53: matches = method.getDeclaringClass().equals(clazz);
54: }
55:
56: return matches;
57:
58: }
59:
60: /**
61: * Returns true if the given object is of type ClassPointcut and
62: * it handles the same class and handlesSubclasses flag is set to the
63: * same value
64: */
65: public boolean equals(Object obj) {
66: if (!(obj instanceof ClassPointcut))
67: return false;
68:
69: ClassPointcut classPointcut = (ClassPointcut) obj;
70:
71: return (clazz.equals(classPointcut.clazz) && matchSubclasses == classPointcut.matchSubclasses);
72: }
73:
74: public int hashCode() {
75: // as per "Effective Java Programming"
76: int result = 17;
77: result = 37 * result + clazz.hashCode();
78: result = 37 * result + (matchSubclasses ? 0 : 1);
79: return result;
80: }
81:
82: }
|