遍历对象层次结构

发布于 2024-12-18 21:13:04 字数 168 浏览 2 评论 0原文

我正在寻找在 Java 中遍历任意对象层次结构的方法。显然,直接使用反射 API 是一种选择,但是在其之上构建哪些库可以使任务变得更容易?

具体来说,我想获取从实现给定接口的基础对象直接或间接引用的所有对象。层次结构可以包含循环,尽管我正在查找的对象将形成 DAG,因此理想情况下我希望它们按拓扑顺序返回。

I'm looking for ways to traverse an arbitrary object hierarchy in Java. Obviously, using the reflection API directly is one option but what libraries are built on top of it that could make the task easier?

Specifically I want to grab all the objects referenced directly or indirectly from a base object that implement a given interface. The hierarchy can contain loops, although the objects I'm looking for will form a DAG, so ideally I'd want them to be returned in topological order.

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

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

发布评论

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

评论(2

弃爱 2024-12-25 21:13:04

你看过 Apache BeanUtils 了吗? -> http://commons.apache.org/beanutils/

我不知道它们是否涵盖了您的所有内容需要,但它非常好且易于使用。

Did you look at Apache BeanUtils yet? -> http://commons.apache.org/beanutils/

I don't know if they cover everything you need but it's quite good and easy to use.

九局 2024-12-25 21:13:04

这是一个建议。如果您的对象实现了 MyObject 接口,则以下代码将遍历所有组件并将其提取到 map 中。

public interface MyObject{
      String getName();
      void addChild(MyObject obj);
      MyObject[] getChildren();
}   

// This will visit and extract all children
public void visitMyObject(MyObject cmp, Map hashMap){
      // Add this component
      if(cmp != null) hashMap.put(cmp.getName(), cmp);
      // Go visit all children
      for(MyObject subComponent : cmp.getChildren()){
          visitMyObject(subComponent, hashMap);
      }
}

Here is a suggestion. If you have your objects implement the MyObject interface, the following will traverse and extract all components to a map.

public interface MyObject{
      String getName();
      void addChild(MyObject obj);
      MyObject[] getChildren();
}   

// This will visit and extract all children
public void visitMyObject(MyObject cmp, Map hashMap){
      // Add this component
      if(cmp != null) hashMap.put(cmp.getName(), cmp);
      // Go visit all children
      for(MyObject subComponent : cmp.getChildren()){
          visitMyObject(subComponent, hashMap);
      }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文