KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jmock > core > constraint > IsEqual


1 /* Copyright (c) 2000-2004 jMock.org
2  */

3 package org.jmock.core.constraint;
4
5 import java.lang.reflect.Array JavaDoc;
6 import org.jmock.core.Constraint;
7
8
9 /**
10  * Is the value equal to another value, as tested by the
11  * {@link java.lang.Object#equals} invokedMethod?
12  */

13 public class IsEqual implements Constraint
14 {
15     private Object JavaDoc object;
16
17     public IsEqual( Object JavaDoc equalArg ) {
18         object = equalArg;
19     }
20
21     public boolean eval( Object JavaDoc arg ) {
22         return areEqual(object, arg);
23     }
24
25     public StringBuffer JavaDoc describeTo( StringBuffer JavaDoc buffer ) {
26         buffer.append("eq(");
27         if (object == null) {
28             buffer.append("null");
29         } else {
30             buffer.append("<");
31             buffer.append(object);
32             buffer.append(">");
33         }
34         buffer.append(")");
35
36         return buffer;
37     }
38
39     private static boolean areEqual( Object JavaDoc o1, Object JavaDoc o2 ) {
40         if (o1 == null || o2 == null) {
41             return o1 == null && o2 == null;
42         } else if (isArray(o1)) {
43             return isArray(o2) && areArraysEqual(o1, o2);
44         } else {
45             return o1.equals(o2);
46         }
47     }
48
49     private static boolean areArraysEqual( Object JavaDoc o1, Object JavaDoc o2 ) {
50         return areArrayLengthsEqual(o1, o2)
51                && areArrayElementsEqual(o1, o2);
52     }
53
54     private static boolean areArrayLengthsEqual( Object JavaDoc o1, Object JavaDoc o2 ) {
55         return Array.getLength(o1) == Array.getLength(o2);
56     }
57
58     private static boolean areArrayElementsEqual( Object JavaDoc o1, Object JavaDoc o2 ) {
59         for (int i = 0; i < Array.getLength(o1); i++) {
60             if (!areEqual(Array.get(o1, i), Array.get(o2, i))) return false;
61         }
62         return true;
63     }
64
65     private static boolean isArray( Object JavaDoc o ) {
66         return o.getClass().isArray();
67     }
68 }
69
Popular Tags