// 根据某个字段判断某个对象是否在一个集合中
使用Predicate和反射机制实现
public static Collection checkList(List list, final String fieldStr,
final String valueStr) {
Predicate predicate = new Predicate() {
@Override
public boolean evaluate(Object obj) {
T t = (T) obj;
Field field;
try {
field = t.getClass().getDeclaredField(fieldStr);
field.setAccessible(true);//获取私有属性的时候必须先设置Accessible为true,然后才能获取
String value = (String) field.get(t);
return valueStr.equals(value);
} catch (NoSuchFieldException e) {
return false;
} catch (IllegalAccessException e) {
return false;
} catch (IllegalArgumentException e) {
return false;
}
}
};
Collection filterResult = CollectionUtils.select(list, predicate);
return filterResult;
}