[英]Reflection: Find an object with inner field value
How can we filter out single object from ArrayList
where we know inner type class, class member ( Field
) and its value? 我们如何从ArrayList
过滤出单个对象,我们知道内部类型类,类成员( Field
)及其值?
pseudo-code: 伪代码:
class MyType {
public String TITLE;
public int ID;
}
ArrayList<MyType> myArray; // filled with data
function findRowByColumnValue(ArrayList<T> array, Field column, Object compareValue){
// list all members of "array"
// and compare the inner field "column" to "compareValue"
}
// called like this
findRowByColumnValue(myArray, MyType.class.getField("ID"), 2);
Here's a generic method that does what you want, except you pass in the field name , rather than the Field
itself, because then you can be sure the Field and Class align. 这是一种通用方法,可以执行所需的操作,除了传递字段名而不是Field
本身,因为这样可以确保Field和Class对齐。 Consider a List with a mixture of instances of different classes, each of type MyClass (but possibly a subclass) - each class may use a different Field for a given column name. 考虑一个混合了不同类实例的列表,每个类都是MyClass类型(但可能是子类)-每个类可以为给定的列名称使用不同的Field。
static <T> List<T> findRowByColumnValue(List<T> array, String column, Object compareValue){
List<T> hits= new ArrayList<T>();
for (T element : array) {
if (element != null && compareValue.equals(
element.getClass().getField(column).get(element))
hits.add(element);
}
return hits;
}
You may optimize by caching the Field for a given Class etc, but I wouldn't initially unless you notice a performance problem. 您可以通过为给定的Class等缓存字段进行优化,但是除非您发现性能问题,否则我不会这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.