01: /*
02: * Copyright (c) 2002-2003 by OpenSymphony
03: * All rights reserved.
04: */
05: package com.opensymphony.webwork.util;
06:
07: import java.lang.reflect.Array;
08: import java.util.Collection;
09: import java.util.Map;
10:
11: /**
12: * <code>ContainUtil</code> will check if object 1 contains object 2.
13: * Object 1 may be an Object, array, Collection, or a Map
14: *
15: * @author Matt Baldree (matt@smallleap.com)
16: * @version $Revision: 2737 $
17: */
18: public class ContainUtil {
19:
20: /**
21: * Determine if <code>obj2</code> exists in <code>obj1</code>.
22: *
23: * <table borer="1">
24: * <tr>
25: * <td>Type Of obj1</td>
26: * <td>Comparison type</td>
27: * </tr>
28: * <tr>
29: * <td>null<td>
30: * <td>always return false</td>
31: * </tr>
32: * <tr>
33: * <td>Map</td>
34: * <td>Map containsKey(obj2)</td>
35: * </tr>
36: * <tr>
37: * <td>Collection</td>
38: * <td>Collection contains(obj2)</td>
39: * </tr>
40: * <tr>
41: * <td>Array</td>
42: * <td>there's an array element (e) where e.equals(obj2)</td>
43: * </tr>
44: * <tr>
45: * <td>Object</td>
46: * <td>obj1.equals(obj2)</td>
47: * </tr>
48: * </table>
49: *
50: *
51: * @param obj1
52: * @param obj2
53: * @return
54: */
55: public static boolean contains(Object obj1, Object obj2) {
56: if ((obj1 == null) || (obj2 == null)) {
57: //log.debug("obj1 or obj2 are null.");
58: return false;
59: }
60:
61: if (obj1 instanceof Map) {
62: if (((Map) obj1).containsKey(obj2)) {
63: //log.debug("obj1 is a map and contains obj2");
64: return true;
65: }
66: } else if (obj1 instanceof Collection) {
67: if (((Collection) obj1).contains(obj2)) {
68: //log.debug("obj1 is a collection and contains obj2");
69: return true;
70: }
71: } else if (obj1.getClass().isArray()) {
72: for (int i = 0; i < Array.getLength(obj1); i++) {
73: Object value = null;
74: value = Array.get(obj1, i);
75:
76: if (value.equals(obj2)) {
77: //log.debug("obj1 is an array and contains obj2");
78: return true;
79: }
80: }
81: } else if (obj1.equals(obj2)) {
82: //log.debug("obj1 is an object and equals obj2");
83: return true;
84: }
85:
86: //log.debug("obj1 does not contain obj2: " + obj1 + ", " + obj2);
87: return false;
88: }
89: }
|