Groovy访问字段类型

时间:2015-10-09 14:05:44

标签: groovy

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

我已尝试使用myObject.metaClass,但我无法使用此API,也许它不是正确的道路?

1 个答案:

答案 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类文档可以派上用场。