You need to sign in to do that
Don't have an account?
OCDGeek
Is it possible to dynamically access class variable
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
Unfortunately I don't think there is. What you are looking for is reflection (at least in the java world), but in Salesforce world you can only access meta information about sobjects and fields.
There's an entry on the idea exchange for this. Not got many points or comments though so I wouldn't hold my breath.
https://sites.secure.force.com/success/ideaview?id=08730000000BrVaAAK
All Answers
Yes, you can do this.
You need to use the Schema Global Describe functions to do this.
I have a blogpost that shows you how to use the Desribe objcts to build a Select ALL statement, but you can use it to grab the dynamic values too.
http://corycowgill.blogspot.com/2011/01/building-dynamic-soql-select-all-query.html
One note: Schema Global Describe is for Custom Objects (I.E. They are tables in the Database AKA SObjects).
I don't think this pattern will work for Apex Only classes (I.E. An Apex Class that is a Value Holder type object with no Custom Object behind the Scenese).
Thanks!
Yeah, I'm familiar with how to do dynamic Apex for SObjects, but I didn't want to make a custom object that corresponds to every class. i just wanted to make sure I wasn't missing something in Apex that allows for this type of dynamic access to Apex-only class variables.
Unfortunately I don't think there is. What you are looking for is reflection (at least in the java world), but in Salesforce world you can only access meta information about sobjects and fields.
There's an entry on the idea exchange for this. Not got many points or comments though so I wouldn't hold my breath.
https://sites.secure.force.com/success/ideaview?id=08730000000BrVaAAK
Thanks for the feedback. I've voted for the idea.
First you need to serialize the contact record, then you parse the json into an apex map and finally use the map to check the values.