001 /* 002 * Created on Oct 2, 2009 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 * 014 * Copyright @2009 the original author or authors. 015 */ 016 package org.fest.assertions; 017 018 import static java.lang.reflect.Array.get; 019 import static java.lang.reflect.Array.getLength; 020 021 import java.util.ArrayList; 022 import java.util.List; 023 024 /** 025 * Understands utility methods for arrays. 026 * 027 * @author Alex Ruiz 028 * 029 * @since 1.2 030 */ 031 public final class ArrayInspection { 032 033 /** 034 * Copies the contents of the given array into a list. 035 * @param array the array to copy. 036 * @return a list containing the contents of the array. 037 * @throws NullPointerException if the given array is <code>null</code>. 038 * @throws IllegalArgumentException if the given object is not an array. 039 */ 040 public static List<Object> copy(Object array) { 041 int length = sizeOf(array); 042 List<Object> copy = new ArrayList<Object>(length); 043 for (int i = 0; i < length; i++) copy.add(get(array, i)); 044 return copy; 045 } 046 047 /** 048 * Returns the size of the given array. 049 * @param array the array. 050 * @return the size of the given array. 051 * @throws NullPointerException if the given array is <code>null</code>. 052 * @throws IllegalArgumentException if the given object is not an array. 053 */ 054 public static int sizeOf(Object array) { 055 validateIsArray(array); 056 return getLength(array); 057 } 058 059 private static void validateIsArray(Object array) { 060 if (array == null) throw new NullPointerException("The array should not be null"); 061 if (!array.getClass().isArray()) throw new IllegalArgumentException("The given object is not an array"); 062 } 063 064 private ArrayInspection() {} 065 }