反射:查找具有内部字段值的对象

发布于 2024-12-20 09:52:45 字数 512 浏览 2 评论 0原文

我们如何从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

第七度阳光i 2024-12-27 09:52:45

这是一个通用方法,可以执行您想要的操作,只不过您传入字段 name,而不是 Field 本身,因为这样您就可以确保字段和类对齐。考虑一个包含不同类实例混合的列表,每个类都是MyClass类型(但可能是子类) - 每个类可以对给定的列名使用不同的字段。

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

您可以通过缓存给定类等的字段来进行优化,但我最初不会,除非您注意到性能问题。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文