1

I have a class with more than 10 attributes (fields).

Each attribute is filled depending of a context (conditions "if"):

if(value == '1'){
 myobject.attribute1 = value;
}else if(value == '2'){
 myobject.attribute2 = value;
}else if(value == '3'){
 myobject.attribute3 = value;
}
...

I think it's a dirty way to process. Is there a good way to automate the process? Something like:

myobject.put('attribute' + value, value);

Currently, Salesforce give me an error:

Method does not exist or incorrect signature: void put(String, String) from the type

How do I do it correctly?

1 Answer 1

4

For a custom class, you won't have any way to set a dynamically named attribute. Other than your if/else chain, the alternative available to you would be a switch statement.

switch on value
{
    when '1' { object.attribute1 = value; }
    when '2' { object.attribute2 = value; }
    ...
    when else { ... }
}

Or, you can loosely type your attributes by just putting them all in a Map<String, String>.

public with sharing class MyClass
{
    public final Map<String, String> attributes = new Map<String, String>();
    public void put(String key, String value)
    {
        attributes.put('attribute' + key, value);
    }
}

Then you could just call

myInstance.put(key, value);

Whether or not loose typing will fit your needs depends on your use case and architectural preferences.

1
  • Thank you for your comment. Your first proposition is better for me because I use a visualforce page to display the result and it reduces the number of lines for the same result.
    – Oupat
    Apr 3, 2020 at 15:45

You must log in to answer this question.

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