Using Reflection with Salesforce Custom Apex Classes—Sort of

If you have ever been coding away on a problem and come to a place where you might need a value of a property on a class or even a specific class without knowing the class name, then you are probably familiar with using reflection. Reflection is essentially a way of modifying the structure and behavior of an object at runtime.

While Salesforce SObjects support a number of various types of reflection, custom Apex classes are very limited. Currently, you are able to determine the class type at runtime:

1
2
Type t = Type.forName(‘MyClass’);
MyClass newObj = (MyClass)t.newInstance();

This is great, but the need that I had was to get the value of a property at runtime when I did not know what property I would actually need. I would have the name of the field as a string at runtime though. This is where the ‘reflection—sort of’ comes in. While this solution works like reflection, it is not technically reflection, just an easy way to do the same thing.

1
2
3
4
5
6
7
8
9
10
11
12
public class YourCustomObject{
public String someField{get;set;}
 
public YourCustomObject(){
this.someField = 'someText';
}
 
public String getField(String fieldName){
Map<String, String> fieldMap = new Map<String, String>{‘someField’ => this.someField};
return (fieldMap.get(fieldName) == null)?'':fieldMap.get(fieldName);
}
}

As you can see there is a method called getField. This method creates a map of all the properties in the class and then will return the requested property’s value.

1
2
YourCustomObject c = new YourCustomObject();
System.assertEquals('someText', c.getField('someField'));

There you have it. Getting the field based off the name at runtime in Apex. There are a number of different ways you could make this better for larger classes but this should help as a starter. Let me know if you have done something similar or if you have a better technique.

This entry was posted in Technology and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>