I need to generate a URL for my RestResource, including the correct namespace. We've been moving the code between an org without a name space, and another org with a temporary namespace. I'd like to write the code so it will work properly during all stages of development, including release.
My current solution is to use a DescribeSObjectResult for one of our custom objects, and compare the getName() value to getLocalName():
global static String namespace()
{
Schema.DescribeSObjectResult D = MyCustomObject__c.sObjectType.getDescribe();
return D.getName().removeEnd( D.getLocalName()).removeEnd( '__');
}
Is there a simpler way to get the namespace?
Update
Based on Axaykumar Varu's answer, I am now using the following:
/*
Retrieve our namespace. Returns Null or the namespace without any adornment.
*/
public static String namespace()
{
ApexClass ac = [SELECT NameSpacePrefix
FROM ApexClass
WHERE Name = 'MyClassName'];
return ac.NameSpacePrefix;
}
The only downside of this current code is that I've had to hard-code the 'MyClassName' portion of the query. I'm not aware of a way to automatically use the name of the class that the code appears in.
namespace()method, you could add the class name as a parameter so that it could be used to get any class' namespace – Brian Miller Feb 06 '19 at 22:43