Predicate接口介绍

1、Predicate是Commons Collections中定义的一个接口。具体

org.apache.commons.collections.Predicate;

 

该接口的源代码如下:

package org.apache.commons.collections;

/**
 * Defines a functor interface implemented by classes that perform a predicate
 * test on an object.
 * <p>
 * A <code>Predicate</code> is the object equivalent of an <code>if</code> statement.
 * It uses the input object to return a true or false value, and is often used in
 * validation or filtering.
 * <p>
 * Standard implementations of common predicates are provided by
 * {@link PredicateUtils}. These include true, false, instanceof, equals, and,
 * or, not, method invokation and null testing.
 * 
 * @since Commons Collections 1.0
 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $
 * 
 * @author James Strachan
 * @author Stephen Colebourne
 */
public interface Predicate {

    /**
     * Use the specified parameter to perform a test that returns true or false.
     *
     * @param object  the object to evaluate, should not be changed
     * @return true or false
     * @throws ClassCastException (runtime) if the input is the wrong class
     * @throws IllegalArgumentException (runtime) if the input is invalid
     * @throws FunctorException (runtime) if the predicate encounters a problem
     */
    public boolean evaluate(Object object);

}

 

2、Predicate接口用来检验某个对象是否满足某个条件。它只是提供简单而明确定义的函数功能而已。Commons Collections也提供了一组定义好的Predicate类供我们使用,这些类都放在:

package org.apache.commons.collections.functors;

 

3、自定义Predicate只需要实现Predicate接口,帮助我们处理额外的业务逻辑。如AndPredicate处理两个Predicate,只有当两者都返回true它才返回true,AnyPredicate处理多个Predicate。当其中一个满足就返回true。等等举例说明:

import java.util.Collection;

import org.apache.commons.collections.Predicate;
/**
 * @author zoopnin
 * 
 * 功能:判读集合中是否存在指定的对象 
 * 
 * 
 */
public class ContainsPredicate implements Predicate {

	private final Collection<?> objs;

	public ContainsPredicate(Collection<?> objs) {
		super();
		this.objs = objs;
	}

	public boolean evaluate(Object object) {
		if (object instanceof Collection<?>) {
			return objs.containsAll((Collection<?>) object);
		} else {
			return objs.contains(object);
		}
	}

}

 

 

 

你可能感兴趣的:(apache)