Dienstag, 5. Juni 2012

Groovy Declared Fields Filter Synthetic

Groovy generates some "synthetic" field to a class, that means the reflection method getDeclaredFields returns more fields than fields which are declared in the Groovy source of a class. To filter the "synthetic" fields the Groovy grep method could be used e.g. "anyClass. declaredFields.grep { !it.synthetic }".

import org.junit.Test
class DeclaredFieldsTest
{
static {
Class.metaClass.getNonSyntheticFields = { ->
delegate.declaredFields.grep { !it.synthetic }
}
}
class Data {
public String name
public int count
static def field(name) { Data.class.getField(name) }
}
@Test void getDeclaredFields() {
def expectedFields = [Data.field('name'), Data.field('count')]
assert expectedFields == Data.class.nonSyntheticFields
}
}
Links