|
| 1 | +/* Copyright (c) 2000-2006 hamcrest.org |
| 2 | + */ |
| 3 | +package org.hamcrest.core; |
| 4 | + |
| 5 | +import org.hamcrest.Formatting; |
| 6 | +import org.hamcrest.Matcher; |
| 7 | +import org.hamcrest.Description; |
| 8 | + |
| 9 | +import java.lang.reflect.Array; |
| 10 | + |
| 11 | + |
| 12 | +/** |
| 13 | + * Is the value equal to another value, as tested by the |
| 14 | + * {@link java.lang.Object#equals} invokedMethod? |
| 15 | + */ |
| 16 | +public class IsEqual implements Matcher { |
| 17 | + private final Object object; |
| 18 | + |
| 19 | + public IsEqual(Object equalArg) { |
| 20 | + object = equalArg; |
| 21 | + } |
| 22 | + |
| 23 | + public boolean match(Object arg) { |
| 24 | + return areEqual(object, arg); |
| 25 | + } |
| 26 | + |
| 27 | + public void describeTo(Description description) { |
| 28 | + description.append("eq(") |
| 29 | + .append(Formatting.toReadableString(object)) |
| 30 | + .append(")"); |
| 31 | + } |
| 32 | + |
| 33 | + private static boolean areEqual(Object o1, Object o2) { |
| 34 | + if (o1 == null || o2 == null) { |
| 35 | + return o1 == null && o2 == null; |
| 36 | + } else if (isArray(o1)) { |
| 37 | + return isArray(o2) && areArraysEqual(o1, o2); |
| 38 | + } else { |
| 39 | + return o1.equals(o2); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + private static boolean areArraysEqual(Object o1, Object o2) { |
| 44 | + return areArrayLengthsEqual(o1, o2) |
| 45 | + && areArrayElementsEqual(o1, o2); |
| 46 | + } |
| 47 | + |
| 48 | + private static boolean areArrayLengthsEqual(Object o1, Object o2) { |
| 49 | + return Array.getLength(o1) == Array.getLength(o2); |
| 50 | + } |
| 51 | + |
| 52 | + private static boolean areArrayElementsEqual(Object o1, Object o2) { |
| 53 | + for (int i = 0; i < Array.getLength(o1); i++) { |
| 54 | + if (!areEqual(Array.get(o1, i), Array.get(o2, i))) return false; |
| 55 | + } |
| 56 | + return true; |
| 57 | + } |
| 58 | + |
| 59 | + private static boolean isArray(Object o) { |
| 60 | + return o.getClass().isArray(); |
| 61 | + } |
| 62 | +} |
0 commit comments