Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails check if a class has a static variable with a particular value

Tags:

grails

groovy

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.

like image 237
rahulserver Avatar asked Feb 08 '23 18:02

rahulserver


2 Answers

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

like image 74
Fernando Avatar answered May 11 '23 08:05

Fernando


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.

like image 24
Joshua Moore Avatar answered May 11 '23 08:05

Joshua Moore