7

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.

1
  • 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 Commented Feb 6, 2019 at 22:43

3 Answers 3

12

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

1
  • 1
    Using the difference between getName and getLocalName is safer since there could be conflicts on YourClassName across packages (or unpackaged code).
    – xn.
    Commented May 22, 2015 at 17:13
7

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

0
2

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, otherwise you need to check the presence of a dot:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .