• Miguel Angel Galvan Ramirez
  • NEWBIE
  • 5 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies

I'm trying to write some validation code for a contact object. I'd like to be able to access different class variables by running through a for loop and validating each variable without having to write out each one.

 

Below is some sample code:

 

public class ContactRecord {
    public String FirstName;
    public String LastName;
    public String Phone;
    public String Email;
}

public static ErrorEntry[] validateContact(ContactRecord contact) {
    ErrorEntry[] errors = new ErrorEntry[]{};
    
    Set<String> reqParams = new Set<String>{'FirstName', 'LastName', 'Email', 'Phone'};
    for (String reqParam : reqParams) {
       if (contact.[reqParam] == null) {
           // log error
       }
    }
    
    return errors;
}

 

Obviously contact.[regParam] produces a syntax error.

 

Is there a syntax in Apex where I can access the contact.FirstName variable by populating the regParam variable with 'FirstName'?

 

This is how I'd do it in Perl, but maybe that has just poluted my thinking. Any help would be appreciated.

 

Steven