是否有一个库可以为我提供另一个类中出现的类的所有实例?

发布于 2025-01-01 09:03:50 字数 687 浏览 1 评论 0原文

我有一个类,它有几个字段,它们是另一个类的子类。我想快速找到顶级类中该子类的所有实例。

例如,

public class TopClass {
 private ClassIWant1 myVar1;
 private ClassIWant2 myVar2;
 private OtherJunk myVar3;
 private Nested myVar4;
}

public class Nested {
 private ClassIWant3 myVar11;
}

public class SuperClass {
}

public ClassIWant1 extends SuperClass {}
public ClassIWant2 extends SuperClass {}
public ClassIWant3 extends ClassIWant1 {}

如果我要使用 TopClass 实例运行该示例,我希望获得一个包含 myVar1、myVar2 和 myVar11 值的列表。

我对如何使用反射手动执行此操作有一个大致的了解,但我希望我不必重新发明轮子。有图书馆可以做到这一点吗?

我熟悉 ReflectUtils,但我不确定它是否可以做到这一点。

I have a class which has several fields which are a subclass of another class. I want to quickly find all instances of that subclass within the top level class.

For example

public class TopClass {
 private ClassIWant1 myVar1;
 private ClassIWant2 myVar2;
 private OtherJunk myVar3;
 private Nested myVar4;
}

public class Nested {
 private ClassIWant3 myVar11;
}

public class SuperClass {
}

public ClassIWant1 extends SuperClass {}
public ClassIWant2 extends SuperClass {}
public ClassIWant3 extends ClassIWant1 {}

If I were to run that example through with an instance of TopClass I would expect to get a List containing the values for myVar1, myVar2, and myVar11.

I have a general idea of how to use reflection to do this manually, but I'm hoping that I don't have to reinvent the wheel. Is there a library that can do this?

I am familiar with ReflectUtils, but I am not sure if that can do this or not.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

放血 2025-01-08 09:03:50

如果我正确理解您的请求,您正在寻找类似的内容:

public class Test {
    public static void main(String[] args) {
        TopClass top = …; // initialise as appropriate
        System.out.println(findFields(top, SuperClass.class));
    }

    private static <T> List<T> findFields(Object haystack, Class<T> needle) {
        return findFields0(haystack, needle, new HashSet<Object>(), new ArrayList<T>());
    }

    private static <T> List<T> findFields0(Object haystack, Class<T> needle, Set<Object> visited, List<T> result) {
        if (visited.contains(haystack)) return result; // we already searched this object

        visited.add(haystack);

        for (Field field : haystack.getClass().getFields()) {
            field.setAccessible(true);
            Object fieldValue = null;
            try {
                fieldValue = field.get(haystack);
            } catch (IllegalAccessException e) {
                // shouldn't happen
                throw new RuntimeException(e);
            }
            if (needle.isAssignableFrom(field.getType())) {
                result.add(needle.cast(fieldValue));
            }

            // recurse
            findFields0(fieldValue, needle, visited, result);
        }
        return result;
    }
}

这通过使用声明的字段的静态类型来工作。也就是说,如果您将一个字段声明为 Object,但它包含 SuperClass 或其后代之一的实例,则不会找到该字段。如果字段将其设置为值,它也会返回 null。我不知道这会对原始类型产生什么影响。

免责声明:代码已在一个乐观的示例上进行了简要测试,如果它导致您的计算机着火,我不承担任何责任。

If I understand your request correctly, you're looking for something like this:

public class Test {
    public static void main(String[] args) {
        TopClass top = …; // initialise as appropriate
        System.out.println(findFields(top, SuperClass.class));
    }

    private static <T> List<T> findFields(Object haystack, Class<T> needle) {
        return findFields0(haystack, needle, new HashSet<Object>(), new ArrayList<T>());
    }

    private static <T> List<T> findFields0(Object haystack, Class<T> needle, Set<Object> visited, List<T> result) {
        if (visited.contains(haystack)) return result; // we already searched this object

        visited.add(haystack);

        for (Field field : haystack.getClass().getFields()) {
            field.setAccessible(true);
            Object fieldValue = null;
            try {
                fieldValue = field.get(haystack);
            } catch (IllegalAccessException e) {
                // shouldn't happen
                throw new RuntimeException(e);
            }
            if (needle.isAssignableFrom(field.getType())) {
                result.add(needle.cast(fieldValue));
            }

            // recurse
            findFields0(fieldValue, needle, visited, result);
        }
        return result;
    }
}

This works by using the static types of the fields as declared. That is, if you declare a field as Object but it holds an instance of SuperClass or one of its descendants, it won't be found. It will also return nulls if the fields have them set as the value. I have no idea what this will do about primitive types.

Disclaimer: Code was tested briefly on an optimistic example, I hold no responsibility if it causes your computer to catch fire.

飞烟轻若梦 2025-01-08 09:03:50

这个方法你在找什么?

Is this method what you're looking for?

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