1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.struts2.util;
22
23 import java.lang.reflect.Array;
24 import java.util.Collection;
25 import java.util.Map;
26
27
28 /***
29 * <code>ContainUtil</code> will check if object 1 contains object 2.
30 * Object 1 may be an Object, array, Collection, or a Map
31 *
32 * @version $Date: 2007-02-21 11:18:24 +0100 (Mi, 21. Feb 2007) $ $Id: ContainUtil.java 509959 2007-02-21 10:18:24Z rgielen $
33 */
34 public class ContainUtil {
35
36 /***
37 * Determine if <code>obj2</code> exists in <code>obj1</code>.
38 *
39 * <table borer="1">
40 * <tr>
41 * <td>Type Of obj1</td>
42 * <td>Comparison type</td>
43 * </tr>
44 * <tr>
45 * <td>null<td>
46 * <td>always return false</td>
47 * </tr>
48 * <tr>
49 * <td>Map</td>
50 * <td>Map containsKey(obj2)</td>
51 * </tr>
52 * <tr>
53 * <td>Collection</td>
54 * <td>Collection contains(obj2)</td>
55 * </tr>
56 * <tr>
57 * <td>Array</td>
58 * <td>there's an array element (e) where e.equals(obj2)</td>
59 * </tr>
60 * <tr>
61 * <td>Object</td>
62 * <td>obj1.equals(obj2)</td>
63 * </tr>
64 * </table>
65 *
66 *
67 * @param obj1
68 * @param obj2
69 * @return
70 */
71 public static boolean contains(Object obj1, Object obj2) {
72 if ((obj1 == null) || (obj2 == null)) {
73
74 return false;
75 }
76
77 if (obj1 instanceof Map) {
78 if (((Map) obj1).containsKey(obj2)) {
79
80 return true;
81 }
82 } else if (obj1 instanceof Collection) {
83 if (((Collection) obj1).contains(obj2) || ((Collection) obj1).contains(obj2.toString())) {
84
85 return true;
86 }
87 } else if (obj1.getClass().isArray()) {
88 for (int i = 0; i < Array.getLength(obj1); i++) {
89 Object value = null;
90 value = Array.get(obj1, i);
91
92 if (value.equals(obj2)) {
93
94 return true;
95 }
96 }
97 } else if (obj1.toString().equals(obj2.toString())) {
98
99 return true;
100 } else if (obj1.equals(obj2)) {
101
102 return true;
103 }
104
105
106 return false;
107 }
108 }