一、前言
关于webwork源码包(2.2.5)中的com.opensymphony.webwork.util.ContainUtil包含工具类,对于集合Collection/Map/Array数组对象间的相当包含关系进行识别判断的代码示例。
二、代码示例
package com.opensymphony.webwork.util;@b@@b@import java.lang.reflect.Array;@b@import java.util.Collection;@b@import java.util.Map;@b@@b@@b@/**@b@ * <code>ContainUtil</code> will check if object 1 contains object 2.@b@ * Object 1 may be an Object, array, Collection, or a Map@b@ *@b@ * @author Matt Baldree (matt@smallleap.com)@b@ * @version $Revision: 2737 $@b@ */@b@public class ContainUtil {@b@@b@ /**@b@ * Determine if <code>obj2</code> exists in <code>obj1</code>.@b@ *@b@ * <table borer="1">@b@ * <tr>@b@ * <td>Type Of obj1</td>@b@ * <td>Comparison type</td>@b@ * </tr>@b@ * <tr>@b@ * <td>null<td>@b@ * <td>always return false</td>@b@ * </tr>@b@ * <tr>@b@ * <td>Map</td>@b@ * <td>Map containsKey(obj2)</td>@b@ * </tr>@b@ * <tr>@b@ * <td>Collection</td>@b@ * <td>Collection contains(obj2)</td>@b@ * </tr>@b@ * <tr>@b@ * <td>Array</td>@b@ * <td>there's an array element (e) where e.equals(obj2)</td>@b@ * </tr>@b@ * <tr>@b@ * <td>Object</td>@b@ * <td>obj1.equals(obj2)</td>@b@ * </tr>@b@ * </table>@b@ *@b@ *@b@ * @param obj1@b@ * @param obj2@b@ * @return@b@ */@b@ public static boolean contains(Object obj1, Object obj2) {@b@ if ((obj1 == null) || (obj2 == null)) {@b@ //log.debug("obj1 or obj2 are null.");@b@ return false;@b@ }@b@@b@ if (obj1 instanceof Map) {@b@ if (((Map) obj1).containsKey(obj2)) {@b@ //log.debug("obj1 is a map and contains obj2");@b@ return true;@b@ }@b@ } else if (obj1 instanceof Collection) {@b@ if (((Collection) obj1).contains(obj2)) {@b@ //log.debug("obj1 is a collection and contains obj2");@b@ return true;@b@ }@b@ } else if (obj1.getClass().isArray()) {@b@ for (int i = 0; i < Array.getLength(obj1); i++) {@b@ Object value = null;@b@ value = Array.get(obj1, i);@b@@b@ if (value.equals(obj2)) {@b@ //log.debug("obj1 is an array and contains obj2");@b@ return true;@b@ }@b@ }@b@ } else if (obj1.equals(obj2)) {@b@ //log.debug("obj1 is an object and equals obj2");@b@ return true;@b@ }@b@@b@ //log.debug("obj1 does not contain obj2: " + obj1 + ", " + obj2);@b@ return false;@b@ }@b@}