0

I have a list that contains an object's parameters that I'd like to access from the object. Below is an example of what I am trying to do

//temp is the name of an object which contains all of the parameters in parameterList
String[] parameterList = new String[]{'field1', 'field5', 'field6'};
Map<String, Object> data = new Map<String, Object>();

for (int i = 0; i < parameterList.length(); i++){
    parameter_value = temp.parameterList.get(i);
    data.add(parameterList.get(i), parameter_value);
}

The problem of course is the first line within the for statement. The string parameterList.get(i) is a string of the parameter I am trying to access from the temp object. How can I access that object parameter from the string?

EDIT: To try and clarify, suppose that earlier on in the code we have that temp.field1 = 5. What I'm trying to do in the for loop is access that value.

EDIT 2: Thanks to the answer below I was able to figure it out. Below is the new code snippet:

String[] parameterList = new String[]{'field1', 'field5', 'field6'};
Map<String, Object> data = new Map<String, Object>();

for (Integer i = 0; i < parameterList.length(); i++){
    data.put(parameterList.get(i), temp.get(parameterList.get(i)));
}
2
  • Your pseudocode doesn't really make sense here, as temp is null and completely unrelated to parameterList.
    – Adrian Larson
    Jul 28 at 15:20
  • @AdrianLarson you're right, temp is an object that is defined much earlier on in the code. I will make that more clear. What's important is that temp is an object and the strings in parameterList contain Strings of parameters of temp. Jul 28 at 15:23
2

To get the value of a field dynamically you should do something like this:

parameter_value = temp.get(parameterList.get(i));

which would look like

parameter_value = temp.get('field1');

This is assuming temp is an object which you queried previously.

You will likely have to cast these values to make them consistent for the map. Like:

String parameter_value = (String) temp.get(parameterList.get(i));
1
  • 1
    Exactly what I was looking for, thank you! Jul 28 at 15:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.