001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.collections4.functors; 018 019import java.io.Serializable; 020import java.util.Objects; 021 022import org.apache.commons.collections4.Predicate; 023 024/** 025 * Predicate implementation that returns true if the input is an instanceof 026 * the type stored in this predicate. 027 * 028 * @since 3.0 029 */ 030public final class InstanceofPredicate extends AbstractPredicate<Object> implements Serializable { 031 032 /** Serial version UID */ 033 private static final long serialVersionUID = -6682656911025165584L; 034 035 /** 036 * Creates the identity predicate. 037 * 038 * @param type the type to check for, may not be null 039 * @return the predicate 040 * @throws NullPointerException if the class is null 041 */ 042 public static Predicate<Object> instanceOfPredicate(final Class<?> type) { 043 return new InstanceofPredicate(Objects.requireNonNull(type, "type")); 044 } 045 046 /** The type to compare to */ 047 private final Class<?> iType; 048 049 /** 050 * Constructor that performs no validation. 051 * Use {@code instanceOfPredicate} if you want that. 052 * 053 * @param type the type to check for 054 */ 055 public InstanceofPredicate(final Class<?> type) { 056 iType = type; 057 } 058 059 /** 060 * Gets the type to compare to. 061 * 062 * @return the type 063 * @since 3.1 064 */ 065 public Class<?> getType() { 066 return iType; 067 } 068 069 /** 070 * Evaluates the predicate returning true if the input object is of the correct type. 071 * 072 * @param object the input object 073 * @return true if input is of stored type 074 */ 075 @Override 076 public boolean test(final Object object) { 077 return iType.isInstance(object); 078 } 079 080}