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
Pranavaditya KannojooPranavaditya Kannojoo 

Code to reference a standard Object dynamically

We have some apex classes which refer to ChatterConversationMessage (standard object) and use the data from the same. This object has details of private message and we could capture the same as expected. When we disable Private Messaging feature in salesforce, this object is non-existent and salesforce complains that our package has to be re-compiled. 

I would like to know if there is any mechanism to check if this such an sObject exist and based on that retrieve its fields dynamically. Essentially we would want the same package to work when the sObject ChatterConversationMessage is available or not.
Best Answer chosen by Pranavaditya Kannojoo
Swati GSwati G
Hi,

You can use global describe method.

if(Schema.getGlobalDescribe().get('ChatterConversationMessage') == null){
   // Object is not present
}

All Answers

Swati GSwati G
Hi,

You can use global describe method.

if(Schema.getGlobalDescribe().get('ChatterConversationMessage') == null){
   // Object is not present
}
This was selected as the best answer
Pranavaditya KannojooPranavaditya Kannojoo
Is there any way where I could retrieve various fields of this object. For e.g. the SObject ChatterMessage contains Body, conversationId. How can I dynamically retrieve those fields without actually referencing the ChatterMessage object.
Swati GSwati G
You can use fields on describe object result as shown below.

Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

if(gd.containsKey('ChatterConversationMessage')){
  Schema.SobjectType chatterConSobjectType = gd.get('ChatterConversationMessage');
  Schema.DescribeSObjectResult d = chatterConSobjectType.getDescribe();
  Map<String, Schema.SObjectField> FsMap = d.fields.getMap();
}


https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_sobject_describe.htm#apex_Schema_DescribeSObjectResult_fields
Pranavaditya KannojooPranavaditya Kannojoo
ok thanks this helped a bit. I also have another query..probably open a new topic on that.