All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.bluecatcode.common.predicates.IsInstancePredicate Maven / Gradle / Ivy

The newest version!
package com.bluecatcode.common.predicates;

import com.google.common.base.Predicate;

import javax.annotation.Nullable;
import java.util.Arrays;

import static com.google.common.base.Preconditions.checkArgument;

/**
 * Checks if the input object is an instance of any of provided class(es)
 */
public class IsInstancePredicate implements Predicate {

    private final Class[] types;

    public IsInstancePredicate(Class[] types) {
        checkArgument(types != null, "Expected non-null types");
        this.types = Arrays.copyOf(types, types.length);
    }

    public static IsInstancePredicate isInstancePredicate(Class[] types) {
        return new IsInstancePredicate(types);
    }

    @Override
    public boolean apply(@Nullable Object input) {
        if (input == null) {
            return false;
        }
        for (Class type : types) {
            boolean isInstance = type.isInstance(input);
            if (isInstance) {
                return true;
            }
        }
        return false;
    }

}