[SalesForce] Variable text string for SObject get method

I want to use a variable string rather than a hard-coded string in my get method.

For example, for every Field in Object A there will be a record in Object B and the record name is the field api name from Object A. I want to reference Object B's name in a Object A dynamic soql query:

String fieldName = objectB.Name
Sobject objectA = Database.query('Select Id From ObjectA__c Where Id = \'' + ObjectB.Object_A_Id__c + '\' Limit 1');
objectB.Number_Field__c = (integer)objectA.get(fieldName);

​I don't know if this is possible. I get the error System.TypeException: Invalid conversion from runtime type Id to Integer. Still new to Apex coding.

Best Answer

As I understand your question:

  1. ObjectB records will have the NAME field set to the API name of a field in ObjectA
  2. You want to populate ObjectA field specified by ObjectB.Name with a value

For example

sObject objectB = [Select Name, Value__c From ObjectB Where Id = 'XYZ'];
ObjectA__c.put(objectB.Name,objectB.Value__c);

For the most part if the field types are the same you should be ok. BUT, if the field types are different then you are going to have to identify the appropriate type and cast it by ([TYPE])objectB.get('Value__c');

Maybe more clear

String fieldName = 'AccountId';
sObject opp = database.query('Select Id ' + fieldName + ' From opportunity Where Id = XYZ');
Contact objectB = New Contact(AccountId = (Id)opp.get(fieldName));

Or maybe I did not follow what you are trying to do with the code