function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
vikas  malikvikas malik 

How do I dynamically reference a field on an object

List<Test_Object__c> testObject = new List<Test_Object__c>();
testObject = [SELECT Id, Field1__c, Field2__c FROM TestObject__c]
String FieldNameNeeded = 'Field1__c';
for (Test_Object__c test : testObject) {
    FieldValueNeeded = test.Field1__c; //hardcoded field name
Best Answer chosen by vikas malik
Gaurav NirwalGaurav Nirwal

You can use the .get method
view source
print?1 String fieldName = 'Field1__c';
for (Test_Object__c test: testObject) {
String result = test.get(fieldName);