-2

Basically I want to write a function that takes list of type T and searches for a given value with given field name.

@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;
}

Any ideas?

If the field (getField) does not exist, then it should simply return false.

4

4 回答 4

1

Your method is not generic and since it should accept any type of object you can change list type to 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; 
}

You could create a supertype and make your method as follows (to avoid using reflection) -

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

But the problem with that approach is that it would be constrained to certain field(s).

于 2013-06-19T00:23:19.863 回答
0

You should be able to create a generic entity A and have a getField method in that entity. Thereafter, use List < T extends A > to ensure that getField can be used.

Alternatively, you can use reflection to check if the getField method exists. But this would be slow.

于 2013-06-19T00:20:28.870 回答
0

Consider the flollwoing Example.

        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;
          }
于 2013-06-19T00:38:24.533 回答
0

Reflection is what you need to look into.

Although hand-crafting using Reflection is going to work, given you have mentioned getField, I strongly suggest you look into all those bean utilities.

For example, Apache Commons BeanUtils

You can do something like :

return PropertyUtils.isReadable(obj, field)
       && value.equals(PropertyUtils.getSimpleProperty(obj, field));
于 2013-06-19T01:50:07.673 回答