遍历T类型的列表并搜索一个值



基本上我想写一个函数,它接受类型为T的列表,并使用给定的字段名搜索给定的值。

@SuppressWarnings("unchecked")
public static boolean listContains( List<T> source, String field, String value ) {
     for ( T t : source ) {
         if ( t.get[field]().equals(value) ) // the getField needs to be dynamic. reflection only way? 
             return true;
     }
     return false;
}

任何想法?

如果字段(getField)不存在,那么它应该简单地返回false

你的方法不是通用的,因为它应该接受任何类型的对象,你可以将列表类型更改为List<?> source

public static boolean listContains(List<?> source, String field, String value) {
    for (Object obj : source ) {
        try {
            Field f = obj.getClass().getDeclaredField(field); //get the field using name
            f.setAccessible(true);
            Object val = f.get(obj); //the value of the field in the current object
            if(value.equals(val)) { //if it equals to passed value
                return true;        //return true
            }
        } catch (NoSuchFieldException e) { //if the object doesn't have the field
            return false;                  //return false
        } catch (Exception e) { //their are other exceptions
            throw new RuntimeException(e); //how ever you want to handle
        }
    }
    return false; 
}

您可以创建一个超类型并使您的方法如下(以避免使用反射)-

public static boolean listContains(List<? extends MyObject> source, String value) {        
    for (MyObject obj : source ) {
        //...
        //... value.equals(obj.getField())
    }
    //...

但是这种方法的问题是,它将被限制在某些字段

您应该能够创建一个通用实体a,并在该实体中使用getField方法。此后,使用List 以确保getField可以被使用。

或者,您可以使用反射来检查getField方法是否存在。但这将是缓慢的。

考虑下面的例子:

        public class BST<E extends Comparable<E>> 
            extends AbstractTree<E> {
            protected TreeNode<E> root;
            protected int size = 0;
           /** Create a default binary tree */
             public BST() {
            }
           /** Create a binary tree from an array of objects */
          public BST(E[] objects) {
          for (int i = 0; i < objects.length; i++)
          insert(objects[i]);
          }
          @Override /** Returns true if the element is in the tree */
          public boolean search(E e) {
          TreeNode<E> current = root; // Start from the root
          while (current != null) {
          if (e.compareTo(current.element) < 0) {
          current = current.left;
          }
          else if (e.compareTo(current.element) > 0) {
          current = current.right;
          }
          else // element matches current.element
          return true; // Element is found
          }
          return false;
          }

反射是你需要研究的。

虽然手工制作使用反射将工作,鉴于你已经提到了getField,我强烈建议你看看所有这些bean实用程序。

例如Apache Commons BeanUtils

你可以这样做:

return PropertyUtils.isReadable(obj, field)
       && value.equals(PropertyUtils.getSimpleProperty(obj, field));

相关内容

最新更新