I have a class in grails like:
class Autoresponder {
static String TYPE_NONE = "none"
static String TYPE_GETRESPONSE = "GetResponse"
static String TYPE_MAILCHIMP = "MailChimp"
static String TYPE_AWEBER = "AWeber"
static String TYPE_INFUSIONSOFT = "InfusionSoft"
static String TYPE_ICONTACT = "iContact"
static String TYPE_SENDY = "Sendy"
static String TYPE_ACTIVECAMPAIGN = "ActiveCampaign"
static String TYPE_API_ACTIVATE = "activate"
static String TYPE_ONTRAPORT = "ontraport"
//rest of code
}
I want to simply find that the above class has a static variable with value AWeber
.
How do I do it? Is there a way to fetch all static user defined variables in a class(and thereby compare each variable's value with what I want)?
EDIT: Due to some technical reasons, I can not change class definition.
Just iterate over all static fields looking for the one with the desired value. As in the following groovy script example
import static java.lang.reflect.Modifier.isStatic
class Autoresponder {
static String TYPE_NONE = "none"
static String TYPE_GETRESPONSE = "GetResponse"
static String TYPE_MAILCHIMP = "MailChimp"
static String TYPE_AWEBER = "AWeber"
static String TYPE_INFUSIONSOFT = "InfusionSoft"
static String TYPE_ICONTACT = "iContact"
static String TYPE_SENDY = "Sendy"
static String TYPE_ACTIVECAMPAIGN = "ActiveCampaign"
static String TYPE_API_ACTIVATE = "activate"
static String TYPE_ONTRAPORT = "ontraport"
}
def getStaticAttributeWithValue(Class clazz, Object searchedValue) {
clazz.declaredFields
.findAll{ isStatic(it.modifiers) }
.find { clazz[it.name] == searchedValue }
}
assert getStaticAttributeWithValue(Autoresponder, "AWeber") != null
assert getStaticAttributeWithValue(Autoresponder, "NonExist") == null
If the function returns null, there is no static field with that value, otherwise, it will be not null. (actually it will be a object of type java.lang.reflect.Field)
There is another way to fetch all static attributes in your class, that is using groovy MetaClass, but the idea is the same
def getStaticAttributeWithValue(Class clazz, Object searchedValue) {
clazz.metaClass.properties
.findAll{ it.getter.static }
.find { clazz[it.name] == searchedValue }
}
This way you will get a groovy.lang.MetaBeanProperty instead
The easiest way would be to use GrailsClassUtils.getStaticFieldValue to see if a Groovy class in Grails has a static property with a given value.
The above utility class has other methods that you may also find helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With