动态寻址类变量

发布于 2024-10-07 08:19:45 字数 373 浏览 2 评论 0原文

我不太确定我能做到这一点,但我愿意。我正在读取一个 XML 文件,在某些节​​点上有大量属性,我最终将它们存储在对象内部的变量中。目前,我解析节点,获取属性名称,然后通过大量的 if/then/else 以便能够将其存储在正确的对象变量中。所有这些都工作得很好。

我希望能够做的是更加动态地进行操作,拥有一个将属性名称映射到对象中的变量名称的映射机制。
因此,例如,如果我有一个 node ,我可以将数据映射到我的对象中的 object.city 和 object.addr ,而不必为我捕获的每个属性进行硬编码的 if/then 。我有几个节点/对象,我这样做,虽然它不经常改变,但我认为像我描述的那样映射它会更干净。

在 Java 中是否有可能实现类似的功能?

非常感谢。

I am not too sure I can do this, but I'd like to. I am reading in an XML file and on some of the nodes there are a good number of attributes that I end up storing in variable inside of an object. Currently, I parse through the nodes, get the attribute names and then go through a very large of if/then/elses to be able to store it in the correct object variable. All of this works just fine.

What I would like to be able to do is do it a little more dynamically, have a mapping mechanism that maps the attribute name to the variable name in the object.
So, for example, if I have a node , I could map the data to say, object.city and object.addr in my object without having to have a hardcoded if/then for each attribute I capture. I have several nodes/objects I do this for, and although it doesn't change that often, I think it would be cleaner to map it like I described.

Is something like that even possible in Java ?

many thanks.

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

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

发布评论

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

评论(2

不喜欢何必死缠烂打 2024-10-14 08:19:45

Yes, you can access fields and methods of a class using the Reflection API. But if your goal is only to read an XML file, don't reinvent the wheel -- just use an existing library such as JAXB.

豆芽 2024-10-14 08:19:45

有许多 POJO-XML 映射实用程序。 Apache 的 XML bean 和 Sun 的 JAXB 是两个常见的 bean。

这是 XMLBeans 教程: http://xmlbeans.apache.org/documentation/tutorial_getstarted.html

There are many POJO-XML mapping utilities. Apache's XML beans and Sun's JAXB are two common ones.

Here is an XMLBeans tutorial: http://xmlbeans.apache.org/documentation/tutorial_getstarted.html

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