反射:查找具有内部字段值的对象
我们如何从 ArrayList
中过滤出我们知道内部类型类、类成员(Field
)及其值的单个对象?
伪代码:
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);
How can we filter out single object from ArrayList
where we know inner type class, class member (Field
) and its value?
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个通用方法,可以执行您想要的操作,只不过您传入字段 name,而不是
Field
本身,因为这样您就可以确保字段和类对齐。考虑一个包含不同类实例混合的列表,每个类都是MyClass类型(但可能是子类) - 每个类可以对给定的列名使用不同的字段。您可以通过缓存给定类等的字段来进行优化,但我最初不会,除非您注意到性能问题。
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. 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.You may optimize by caching the Field for a given Class etc, but I wouldn't initially unless you notice a performance problem.