Q:

Groovy access field type

Using Groovy, how can I find out if a field field of a given instance myObject is a List?
I have tried using myObject.metaClass, but I don't get anywhere with this API, maybe it's not the right path ?

A:

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.

