2013-06-19 4 views
-2

기본적으로 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를 반환해야합니다.

+0

- 제가 포인트를? 질문에 무슨 문제가 있습니까? –

답변

1

귀하의 방법은 일반적인 것이 아니며 모든 유형의 개체를 받아 들일 수 있으므로 목록 유형을 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()) 
    } 
    //... 

을하지만 그 접근 방식의 문제는 그것이 특정 분야로 제한 될 것입니다 (에스).

0

일반 엔터티 A를 만들고 해당 엔터티에 getField 메서드가 있어야합니다. 그런 다음 List < T extends A>를 사용하여 getField를 사용할 수 있도록하십시오.

또는 반향을 사용하여 getField 메소드가 있는지 확인할 수 있습니다. 그러나 이것은 느릴 것입니다.

0

음모 예제를 고려하십시오.

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

반사를 조사해야합니다.

Reflection을 사용하여 수작업으로 만들려고해도 getField을 언급 했으므로 모든 콩 유틸리티를 살펴볼 것을 강력히 권합니다. 예를 들어

, Apache Commons BeanUtils

당신은 같은 것을 수행 할 수 있습니다

return PropertyUtils.isReadable(obj, field) 
     && value.equals(PropertyUtils.getSimpleProperty(obj, field)); 
관련 문제