如何在groovy中检索嵌套属性
我想知道在 Groovy 中检索嵌套属性的最佳方法是什么,采用给定的对象和任意“属性”字符串。我想要这样的事情:
someGroovyObject.getProperty("property1.property2")
我很难找到其他人想要这样做的例子,所以也许我不理解一些基本的 Groovy 概念。看来必须有一些优雅的方法来做到这一点。
作为参考,Wicket 中有一个功能正是我正在寻找的,称为 PropertyResolver: http://wicket.apache.org/apidocs/1.4/org/ apache/wicket/util/lang/PropertyResolver.html
任何提示将不胜感激!
I'm wondering what is the best way to retrieve nested properties in Groovy, taking a given Object and arbitrary "property" String. I would like to something like this:
someGroovyObject.getProperty("property1.property2")
I've had a hard time finding an example of others wanting to do this, so maybe I'm not understanding some basic Groovy concept. It seems like there must be some elegant way to do this.
As reference, there is a feature in Wicket that is exactly what I'm looking for, called the PropertyResolver:
http://wicket.apache.org/apidocs/1.4/org/apache/wicket/util/lang/PropertyResolver.html
Any hints would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不知道 Groovy 是否有内置的方法来做到这一点,但这里有 2 个解决方案。在 Groovy 控制台 中运行此代码进行测试。
I don't know if Groovy has a built-in way to do this, but here are 2 solutions. Run this code in the Groovy Console to test it.
Groovy Beans 让您可以直接访问字段。您不必定义 getter/setter 方法。它们是为您生成的。每当您访问 bean 属性时,都会在内部调用 getter/setter 方法。您可以使用 .@ 运算符来绕过此行为。请参阅以下示例:
如果您不处理集合,则只需调用要访问的字段即可。
如果要访问集合中的字段,则必须选择该元素:
Groovy Beans let you access fields directly. You do not have to define getter/setter methods. They get generated for you. Whenever you access a bean property the getter/setter method is called internally. You can bypass this behavior by using the .@ operator. See the following example:
If you are not dealing with collections you can simply just call the field you want to access.
If you want to access a field within a collection you have to select the element:
您还可以使用
propertyMissing
。这就是您可能所说的 Groovy 的内置方法。在您的类中声明这一点:
然后根据需要引用您的属性:
这是自动递归的,您不必显式调用方法。这只是一个 getter,但您也可以使用参数定义第二个版本来创建 setter。
缺点是,据我所知,您只能定义一个版本的
propertyMissing
,因此您必须决定动态路径导航是否是您想要使用它的用途。You can also use
propertyMissing
. This is what you might call Groovy's built-in method.Declare this in your class:
Then refer to your properties as desired:
This is automatically recursive, and you don't have to explicitly call a method. This is only a getter, but you can define a second version with parameters to make a setter as well.
The downside is that, as far as I can tell, you can only define one version of
propertyMissing
, so you have to decide if dynamic path navigation is what you want to use it for.请参阅
https://stackoverflow.com/a/15632027/2015517
它使用 ${} 语法,可以用作一部分GString 的
See
https://stackoverflow.com/a/15632027/2015517
It uses ${} syntax that can be used as part of GString