Created
December 28, 2015 17:32
-
-
Save davidkuster/25e7325b12cd6ec46048 to your computer and use it in GitHub Desktop.
Util to get the fields defined on a class, as well as converting objects to maps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// TODO: think about whether this makes more sense as a trait... | |
class ClassUtils { | |
// exclude all fields that start with these prefixes from the list returned by getFields() method | |
private static final List<String> EXCLUDED_FIELD_PREFIXES = ['grails_', '$', '__'] | |
// Added exclusion of "grails_" and "$" fields - causes problems with Validateable cmd objs. | |
// Added exclusion of "__" due to Cobertura adding "__cobertura_counters" field. | |
/** | |
* Retrieve the names of all the non-synthetic fields on a class. That is, all the fields | |
* that a programmer added, not all the weirdness that Groovy et al throw in there. | |
* | |
* This may be useful for testing and data mapping purposes. | |
* | |
* @param clazz The input class | |
* @return A list of field names | |
*/ | |
static List<String> getFields(Class clazz) { | |
if (! clazz) return [] | |
clazz.declaredFields.findAll { | |
! it.synthetic && ! EXCLUDED_FIELD_PREFIXES.any { prefix -> it.name.startsWith(prefix) } | |
}*.name | |
} | |
/** | |
* Retrieve the defined fields and values from the given object as a map. | |
* | |
* Again, presumably useful for testing and data mapping purposes. | |
* | |
* @param obj The object from which to retrieve the properties | |
* @return The map of field names as keys and property values as values | |
*/ | |
static Map toMap(obj) { | |
if (! obj) return [:] | |
List<String> fields = getFields(obj.getClass()) | |
fields.collectEntries { field -> | |
[ (field): obj."${field}"] | |
} | |
} | |
/** | |
* Retrieve the defined fields and values from the given object as a map, | |
* but limit the returned fields to those specified in the fieldList input. | |
* | |
* @param obj The object from which to retrieve the properties | |
* @param fieldList The list of fields to return | |
* @return The map of field names as keys and property values as values | |
*/ | |
static Map toMap(obj, List<String> fieldList) { | |
if (! obj || ! fieldList) return [:] | |
List<String> fields = getFields(obj.getClass()) | |
fields.intersect(fieldList).collectEntries { field -> | |
[ (field): obj."${field}"] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment