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.

  • As for your 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 6 '19 at 22:43

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'];

| 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).

| improve this answer | |

If you know the name of the class, try this solution (inspired by this post):

String namespace = MyClass.class.getName().split('\\.')[0];

(NOTE: This only works if you for sure are working within a managed package)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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