26 September 2015

Written by Jon Bevan

Actually, I think this just uses the Java reflection packages, but anyway...

I'd not done any reflection before in Java or Groovy and ended up wanting to do some for a workflow export script for a customer.

Specifically I wanted to iterate over the public fields of a class as they were being used as constants to store custom field names:

public class CustomFields {
    public final static String CF_PLATFORM  = "Platform Response"
    public final static String CF_FUNC_TEAM = "Functional Team Response"

    // Platforms relevant to specific requirement
    public final static String CF_IMPACTED_PLATFORMS       = "Impacted Platform/s"
    public static final String CF_LEAD_PLATFORM            = 'Lead Platform'

    // Corresponding Groups for Issue Security Level
    public final static String CF_IMPACTED_OFFERING_GROUPS = "Impacted Offering Groups"

    // cross-product field representing those who have not replied
    public final static String CF_NO_RESPONSE_FROM = "No response from"

    // cross-product field representing those who said No Impact
    public final static String CF_NO_IMPACT = "No Impact Platforms/Teams"
}

Turns out its quite easy, you can do the following to get a list of the values of those public fields:


final CustomFields cf = new CustomFields()
final Field[] customFieldDefns = CustomFields.class.getDeclaredFields()

final String[] values = customFieldDefns.findAll {
    // For those who don't know, the magic variable 'it' here refers to the current element in the collection
    Modifier.isPublic(it.modifiers) 
}.collect { Field f ->
    // This returns the value of the field from the cf object (instance of CustomFields)
    f.name + " has value: " + f.get(cf) 
}

Now values contains the entries:

  • CF_PLATFORM has value: Platform Response
  • CF_FUNC_TEAM has value: Functional Team Response
  • etc :)


blog comments powered by Disqus