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;
020
021import org.apache.commons.collections4.Predicate;
022
023/**
024 * Predicate implementation that returns true if the input is an instanceof
025 * the type stored in this predicate.
026 *
027 * @since 3.0
028 * @version $Id: InstanceofPredicate.html 972421 2015-11-14 20:00:04Z tn $
029 */
030public final class InstanceofPredicate implements Predicate<Object>, Serializable {
031
032    /** Serial version UID */
033    private static final long serialVersionUID = -6682656911025165584L;
034
035    /** The type to compare to */
036    private final Class<?> iType;
037
038    /**
039     * Factory to create the identity predicate.
040     *
041     * @param type  the type to check for, may not be null
042     * @return the predicate
043     * @throws IllegalArgumentException if the class is null
044     */
045    public static Predicate<Object> instanceOfPredicate(final Class<?> type) {
046        if (type == null) {
047            throw new IllegalArgumentException("The type to check instanceof must not be null");
048        }
049        return new InstanceofPredicate(type);
050    }
051
052    /**
053     * Constructor that performs no validation.
054     * Use <code>instanceOfPredicate</code> if you want that.
055     *
056     * @param type  the type to check for
057     */
058    public InstanceofPredicate(final Class<?> type) {
059        super();
060        iType = type;
061    }
062
063    /**
064     * Evaluates the predicate returning true if the input object is of the correct type.
065     *
066     * @param object  the input object
067     * @return true if input is of stored type
068     */
069    public boolean evaluate(final Object object) {
070        return iType.isInstance(object);
071    }
072
073    /**
074     * Gets the type to compare to.
075     *
076     * @return the type
077     * @since 3.1
078     */
079    public Class<?> getType() {
080        return iType;
081    }
082
083}