Groovy访问字段类型

Groovy访问字段类型,groovy,Groovy,使用Groovy,如何确定给定实例myObject的字段field是否为列表 我尝试过使用myObject.metaClass,但是这个API没有任何效果,也许它不是正确的路径?类Foo扩展栏{ class Foo extends Bar { public def someField = new ArrayList<String>() } class Bar { private List anotherField = null } def foo = new Foo(

使用Groovy,如何确定给定实例
myObject
的字段
field
是否为
列表

我尝试过使用
myObject.metaClass
,但是这个API没有任何效果,也许它不是正确的路径?

类Foo扩展栏{
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]
public def someField=new ArrayList() } 分类栏{ private List anotherField=null } def foo=新foo() println(foo.someField.class)//class java.util.ArrayList println(List.class.isInstance(foo.someField))//true println(foo.someField instanceof List)//true //如果需要,还可以通过反射获得场: println(foo.class.getDeclaredField(“someField”).get(foo.class)//class java.util.ArrayList println() def otherField=foo.class.superclass.getDeclaredField(“另一个字段”) println(otherField)//private java.util.List Bar.anotherField println(otherField.type)//接口java.util.List otherField.accessible=true set(foo,新的ArrayList([1,2])) println(otherField.get(foo))/[1,2]

类文档对此很方便。

如果someField初始化为null,如“public List someField=null”,并且如果它是父对象的私有字段,只能通过其getter访问,该怎么办?