<< What is a three-tier architecture? (什么是三层架构?) | 首页 | 30个免费(并开源)的基本的Windows软件 >>

实现Predicate接口,在对象集合里查找对象

之前写过一篇使用Collections实现java.util.Comparator接口,对对象集合进行多属性组合排序 ,下面是一个Predicate的实现类,使用它可以在对象集合里通过设置属性条件查找对象。这也是通过commons.collections对Collections使用的一个例子。

 

import java.math.BigDecimal;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.Predicate;

/**
 * 实现断言Predicate,用于从Collection里查找符合条件的对象
 * 例如1:
 * Predicate predicate =new PredicateImpl("age",new Integer(5));
 * List rtns=(List)CollectionUtils.select(lists,predicate);
 *
 * 例如2:
 * Predicate predicate1 =new PredicateImpl("age",new Integer(5));
 * Predicate predicate2 =new PredicateImpl("grade","A");
 * Predicate any = PredicateUtils.allPredicate(new Predicate[]{predicate1, predicate2});//两个全部判断
 * List ddd=(List)CollectionUtils.select(lists,any);
 *
 * <p>Title: is a Class</p>
 *
 * <p>Description: 类</p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: sunrise</p>
 *
 * @author islph
 * @version 1.0
 */
public class PredicateImpl implements Predicate {
    private String property;

    private Object value;

    public PredicateImpl(String property, Object value) {
        this.property = property;
        this.value = value;
    }

    public boolean evaluate(Object object) {

        try {
            Object beanValue;
            if (property.indexOf(".") > 0) {
                beanValue = PropertyUtils.getNestedProperty(object, property);
            } else {
                beanValue = PropertyUtils.getProperty(object, property);
            }
            if (beanValue == null) {
                return false;
            }
            if (!value.getClass().equals(beanValue.getClass())) {
                throw new RuntimeException("value.class!=beanValue.class");
            }
            return myCompare(beanValue, value);

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }

    private boolean myCompare(Object value, Object beanValue) {
        if (beanValue.getClass().equals(Integer.class)) {
            if (((Integer) beanValue).equals(value)) {
                return true;
            }
        }
        if (beanValue.getClass().equals(BigDecimal.class)) {
            if (((BigDecimal) beanValue).compareTo((BigDecimal) value) == 0) {
                return true;
            }
        }
        if (beanValue.getClass().equals(String.class)) {
            if (beanValue.toString().equals(value.toString())) {
                return true;
            }
        }else{
            if(beanValue.equals(value)){
                return true;
            }
        }
        return false;
    }

}
标签 :



发表评论 发送引用通报