View Javadoc

1   /*
2    * $Id: ContainUtil.java 418521 2006-07-01 23:36:50Z mrdon $
3    *
4    * Copyright 2006 The Apache Software Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.struts2.util;
19  
20  import java.lang.reflect.Array;
21  import java.util.Collection;
22  import java.util.Map;
23  
24  
25  /***
26   * <code>ContainUtil</code> will check if object 1 contains object 2.
27   * Object 1 may be an Object, array, Collection, or a Map
28   *
29   */
30  public class ContainUtil {
31  
32      public static boolean contains(Object obj1, Object obj2) {
33          if ((obj1 == null) || (obj2 == null)) {
34              //log.debug("obj1 or obj2 are null.");
35              return false;
36          }
37  
38          if (obj1 instanceof Map) {
39              if (((Map) obj1).containsValue(obj2)) {
40                  //log.debug("obj1 is a map and contains obj2");
41                  return true;
42              }
43          } else if (obj1 instanceof Collection) {
44              if (((Collection) obj1).contains(obj2)) {
45                  //log.debug("obj1 is a collection and contains obj2");
46                  return true;
47              }
48          } else if (obj1.getClass().isArray()) {
49              for (int i = 0; i < Array.getLength(obj1); i++) {
50                  Object value = null;
51                  value = Array.get(obj1, i);
52  
53                  if (value.equals(obj2)) {
54                      //log.debug("obj1 is an array and contains obj2");
55                      return true;
56                  }
57              }
58          } else if (obj1.equals(obj2)) {
59              //log.debug("obj1 is an object and equals obj2");
60              return true;
61          }
62  
63          //log.debug("obj1 does not contain obj2: " + obj1 + ", " + obj2);
64          return false;
65      }
66  }