0

If I have a map of strings like so:

public static Map<String, String> fieldTranslation() {
    Map<String, String> fieldTranslation = new Map<String, String>();
    fieldTranslation.put('Initial_System_Size__c',     'DEFAULT_INITIAL_SYSTEM_SIZE');
    fieldTranslation.put('System_Production__c',       'DEFAULT_SYSTEM_PRODUCTION');
    return fieldTranslation;
}

How can I write a function to find a key, and "send" each key and value to be evaluated as a variable or attribute?

Something like this (pseudocode):

public static Boolean isDefault(String field) {
    return (eval(fieldTranslation[field]) == (fieldTranslation[field].value()));
}

Any help'd be great. Thanks!

1
  • could you make your map be a set of key => constructed interface objects? each interface would support a method called eval() and the object's constructor would contain the necessary arguments needed to do the calculation?
    – cropredy
    Jan 21, 2016 at 1:11

1 Answer 1

1

If I follow you correctly...

public static Boolean isDefault(SObject record, String field) {
    return record.get(field) == fieldTranslation.get(field);
}

Note that the methods we're talking about are SObject.get and Map.get; you can't do this with any generic object (i.e. we do not have true reflection), but those two methods should point you in the general direction.

7
  • That works for the record.get() part, but I have a variable in the class called DEFAULT_SYSTEM_PRODUCTION which I need to evaluate to get its value.
    – t56k
    Jan 20, 2016 at 22:24
  • I imagine I want something like Decimal.valueOf(fieldTranslation.get(field)), but that returns an invalid decimal.
    – t56k
    Jan 20, 2016 at 22:28
  • Also, just using the variable name in the map (i.e, not in a string) results in what I imagine is some sort of scoping error.
    – t56k
    Jan 20, 2016 at 22:38
  • 1
    Oh. I see what you're getting at. Unfortunately, we don't have proper reflection, which limits your options. Most likely, you'd want something like a Map<String, Object>, which is as close as you can get to dynamic references.
    – sfdcfox
    Jan 20, 2016 at 22:39
  • 1
    @CD-RUM Keys must be unique, so you couldn't have two possible values. Using the Map<String, Object> variable, you could have either a list or a single value, and then determine which one to use: Object defaults = fieldTranslation.get('System_Production__c'); if(defaults instanceOf List<String>.class) { /* compare as list */ } else { /* compare as string */ }. It might get a bit complicated though... Apex Code, being strongly typed, doesn't really support this sort of coding.
    – sfdcfox
    Jan 20, 2016 at 22:58

You must log in to answer this question.

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