1

I have a apex class consisting some static variables, is there any way to get the value of one of these variables dynamically?

Example :

public with sharing class ConstantsClass
{
     public static final String ANIMAL = 'dog';
     public static final String CITY = 'Delhi';
}

public with sharing class MyClass{
      public static String city;
      public static String animal;

      public static String getValueFromConstants(String animal,String city) {
           this.city=ConstantsClass.[city];// Error
}

How can I get the value of city from constants ?

Any Help would be appretiated.

2 Answers 2

2

Unfortunately not, classes don't have the [] operator in Apex and there are no form of reflection either, the best you could do is provide a map in your constants class.

public with sharing class ConstantsClass {
            public static final Map<String, String> animals = new Map<String, String> {
        'example' => 'dog'
    };

    public static final Map<String, String> cities = new Map<String, String> {
        'example' => 'Delhi'
    };
}

Then you can access them as follows:

 ConstantsClass.cities.get(...)

If your class really is just a wrapped around a single list (like in your example) then you could abstract it a tiny bit further.

public with sharing class ConstantsClass {
    public static final String ANIMAL = 'dog';
    public static final String CITY = 'Delhi';

    private static final Map<String, String> constants = new Map<String, String> {
        'ANIMAL' => ANIMAL,
        'CITY' => CITY
    };

    public static String get(String name) {
        return constants.get(name);
    }
}

Then you can access them as follows:

 ConstantsClass.get(...)

Alternatively you could move the declaration of these constants out of Apex all together and store them in a Custom Settings or Custom Metadata, you'll want to use a lazy loading pattern to reduce the number of SOQL queries if these are accessed frequently during a transaction though.

0

To access the value of Static variable in other class, you can directly use the ClassName.StaticVariableName. Like this- ConstantsClass.CITY.

Try this this.city=ConstantsClass.CITY;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .