org.apache.struts2.util.ContainUtil Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.util;
import java.lang.reflect.Array;
import java.util.Map;
/**
* ContainUtil
will check if object 1 contains object 2.
* Object 1 may be an Object, array, Collection, or a Map
*/
public class ContainUtil {
/**
* Determine if obj2
exists in obj1
.
*
*
*
* Type Of obj1
* Comparison type
*
*
* null
* always return false
*
*
* Map
* Map containsKey(obj2)
*
*
* Collection
* Collection contains(obj2)
*
*
* Array
* there's an array element (e) where e.equals(obj2)
*
*
* Object
* obj1.equals(obj2)
*
*
*
*
* @param obj1 first object
* @param obj2 second object
* @return true if first object contains second object or if the are equals, otherwise false
*/
public static boolean contains(Object obj1, Object obj2) {
if ((obj1 == null) || (obj2 == null)) {
return false;
}
if (obj1 instanceof Map) {
if (((Map) obj1).containsKey(obj2)) {
return true;
}
} if (obj1 instanceof Iterable) {
for (Object value : ((Iterable) obj1)) {
if (obj2.equals(value) || (value != null && obj2.toString().equals(value.toString()))) {
return true;
}
}
} else if (obj1.getClass().isArray()) {
for (int i = 0; i < Array.getLength(obj1); i++) {
Object value = Array.get(obj1, i);
if (obj2.equals(value) || (value != null && obj2.toString().equals(value.toString()))) {
return true;
}
}
} else if (obj1.toString().equals(obj2.toString())) {
return true;
} else if (obj1.equals(obj2)) {
return true;
}
return false;
}
}