[英]Groovy access field type
Using Groovy, how can I find out if a field field
of a given instance myObject
is a List
? 使用Groovy,如何确定给定实例
myObject
的字段field
是否为List
?
I have tried using myObject.metaClass
, but I don't get anywhere with this API, maybe it's not the right path ? 我曾尝试使用
myObject.metaClass
,但使用此API却myObject.metaClass
,也许这不是正确的路径?
class Foo extends Bar {
public def someField = new ArrayList<String>()
}
class Bar {
private List anotherField = null
}
def foo = new Foo()
println(foo.someField.class) // class java.util.ArrayList
println(List.class.isInstance(foo.someField)) // true
println(foo.someField instanceof List) // true
// If you wanted, you could also get the field by reflection:
println(foo.class.getDeclaredField("someField").get(foo).class) // class java.util.ArrayList
println()
def otherField = foo.class.superclass.getDeclaredField("anotherField")
println(otherField) // private java.util.List Bar.anotherField
println(otherField.type) //interface java.util.List
otherField.accessible = true
otherField.set(foo, new ArrayList([1, 2]))
println(otherField.get(foo)) // [1, 2]
The Class
class documentation comes in handy for this. Class
类文档对此非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.