[英]How to get class field identifier as String in Groovy?
Suppose simple Groovy class (POGO):假设简单的 Groovy 类(POGO):
class Person { String name; int age }
How to get chosen identifier at runtime?如何在运行时获取选定的标识符? In other words identifier name (like "name" and "age") used in source code by programmer - not value held in variable of this identifier (like "James" and "32").换句话说,程序员在源代码中使用的标识符名称(如“name”和“age”) - 而不是该标识符的变量中保存的值(如“James”和“32”)。
With result solution (if there is any) it would be possible to write something like this (syntactically wrong pseudo code):有了结果解决方案(如果有的话),就可以写出这样的东西(语法错误的伪代码):
assert new Person().name.identifierAsString == 'name'
assert new Person().age.identifierAsString == 'age'
Please note I'm not trying to get list of field names (like Person.declaredFields
), but compile-time safe way to get field identifier as String .请注意,我不是要获取字段名称列表(如Person.declaredFields
),而是以编译时安全的方式获取字段标识符为 String 。
I'm not certain what you're trying to accomplish, but you can get all of the declared field names like so:我不确定您要完成什么,但是您可以获得所有声明的字段名称,如下所示:
assert ['name', 'age'] == Person.declaredFields.findAll { !it.synthetic }.collect { it.name }
And otherwise declaredFields
is a list of java.lang.reflect.Field
that you can use.否则declaredFields
的java.lang.reflect.Field
是您可以使用的java.lang.reflect.Field
列表。
I wrote a lib sometime ago to write type-checked queries.前段时间我写了一个库来编写类型检查的查询。 It might be what you are after:这可能是你所追求的:
import org.latitude.Latitude
Customer customer = Latitude.forClass Customer
assert customer instanceof Customer
assert customer.name == "name"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.