001 /*
002 * Created on Nov 1, 2007
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 @2007 the original author or authors.
015 */
016 package org.fest.util;
017
018 import java.util.ArrayList;
019 import java.util.Collection;
020 import java.util.List;
021
022 /**
023 * Understands filtering elements of a collection by their data type.
024 * @param <T> the generic type of the objects returned by the filter.
025 *
026 * @author Yvonne Wang
027 */
028 public class TypeFilter<T> implements CollectionFilter<T> {
029
030 /**
031 * Creates a new <code>{@link TypeFilter}</code>.
032 * @param <T> the generic type of the target type.
033 * @param type the target type for this filter.
034 * @return the created filter.
035 */
036 public static <T> TypeFilter<T> byType(Class<T> type) {
037 return new TypeFilter<T>(type);
038 }
039
040 private final Class<T> type;
041
042 TypeFilter(Class<T> type) {
043 this.type = type;
044 }
045
046 /**
047 * Filters the given collection by the type specified in this filter.
048 * @param target the collection to filter.
049 * @return a list containing the filtered elements.
050 * @throws IllegalArgumentException if the given collection is <code>null</code>.
051 */
052 @SuppressWarnings("unchecked")
053 public List<T> filter(Collection<?> target) {
054 if (target == null) throw new IllegalArgumentException("The collection to filter should not be null");
055 List<Object> filtered = new ArrayList<Object>();
056 for (Object o : target) {
057 if (o == null) continue;
058 if (type.isAssignableFrom(o.getClass())) filtered.add(o);
059 }
060 return (List<T>)filtered;
061 }
062 }