귀하의 방법은 일반적인 것이 아니며 모든 유형의 개체를 받아 들일 수 있으므로 목록 유형을 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())
}
//...
을하지만 그 접근 방식의 문제는 그것이 특정 분야로 제한 될 것입니다 (에스).
- 제가 포인트를? 질문에 무슨 문제가 있습니까? –