Grails checks if a class has a static variable with a specific value

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 just find that the above class has a static variable with a value AWeber. How can I do it? Is there a way to get all the static user variables in the class (and thereby compare each variable value with what I want)?

EDIT: For some technical reasons, I cannot change the class definition.

+4
source share
3 answers

Just iterate over all the static fields that are looking for the one that has 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

null, , . ( java.lang.reflect.Field)

, groovy MetaClass,

def getStaticAttributeWithValue(Class clazz, Object searchedValue) {
    clazz.metaClass.properties
        .findAll{ it.getter.static }
        .find { clazz[it.name] == searchedValue }
}

groovy.lang.MetaBeanProperty

+4

- GrailsClassUtils.getStaticFieldValue, , Groovy Grails .

, .

+3

MetaClass. - ( ... ):

String val
if(Autoresponder.metaClass.static.AWeber){
    val = Autoresponder.AWeber
}

MetaClass .

+1
source

Source: https://habr.com/ru/post/1612047/


All Articles