使用Groovy,如何确定给定实例field
的字段myObject
是否为List
?
我已尝试使用myObject.metaClass
,但我无法使用此API,也许它不是正确的道路?
答案 0 :(得分:0)
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]
Class
类文档可以派上用场。