[SalesForce] How to get object Prefix from string type of object name

I have following code to return prefix of any object based on API name of object passed as string. :

private static String  getObjectPrefixID(String objName){

        Schema.DescribeSObjectResult r = genericObject.sObjectType.getDescribe();
        String keyPrefix = r.getKeyPrefix();
        return keyPrefix;
    }

I am getting error as:

Initial term of field expression must be a concrete SObject: String

Not sure how to get the prefix ID in this case.

Best Answer

You can do something like

Map<String, Schema.SObjectType> m  = Schema.getGlobalDescribe() ;
system.debug('==>m is==>'+m);
Schema.SObjectType s = m.get('Account') ;
system.debug('==>Sobject Type is ==>'+s);
Schema.DescribeSObjectResult r = s.getDescribe() ;
String keyPrefix = r.getKeyPrefix();
return keyPrefix;

Replace Account with your Object API name.

Related Topic