Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?


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.

share|improve this question
up vote 9 down vote accepted

Salesforce provides a standard object called ApexClass, by using this object you can get the Namespace.

Query on ApexClass:

ApexClass ac = [SELECT NameSpacePrefix FROM ApexClass WHERE Name = 'YourClassName'];

share|improve this answer
Using the difference between getName and getLocalName is safer since there could be conflicts on YourClassName across packages (or unpackaged code). – xn. May 22 '15 at 17:13

The UserInfo.isCurrentUserLicensed(String) method can be used for this without a SOQL query.

If the namespace passed in isn't valid in the current org (due to the package not being installed) a TypeException is thrown, which would indicate you're working with an unmanaged version of your codebase.

If the method returns true you're in a managed environment, and false means you're in a managed environment but aren't licensed for the package (which wouldn't happen in the packaging org).

share|improve this answer
Nice trick, thanks! – jkraybill Dec 28 '12 at 0:37

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.