动态寻址类变量
我不太确定我能做到这一点,但我愿意。我正在读取一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以使用 Reflection API。但是,如果您的目标只是读取 XML 文件,请不要重新发明轮子 - 只需使用现有的库,例如
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.
有许多 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