Get Namepsace for code at runtime?

I am in an apex class. Is it possible to get the namespace for this class at runtime?
Reason, I serialise a pile of objects to JSON and the namespace is pre-appended on all the attributes. I wish to remove it.

If I can find out the namespace at runtime, I can just do a String.replace()

Any help much appreciated?

Answer

You can detect the namespace for the current class through the use of Type reflection. Here’s a class I came up with for testing purposes:

public class DemoClass {
    public static string getNamespace() {
        String[] parts = String.valueOf(DemoClass.class).split('\\.',2);
        if(parts.size() > 1 && Type.forName(parts[0],parts[1]) != NULL && Type.forName(parts[0],parts[1])==DemoClass.class) {
            return parts[0];
        }
        return '';
    }
}

This class converts the name of the class to a string, splits it into two parts, and tries to retrieve the class through a (possible) namespace. If there is only one part, the class has no namespace. If there are two parts, it may be an inner class or a namespaced class; we can test for this by requesting a Type instance and seeing if we get a valid value that matches the class we are testing for. If so, we’ve found our namespace, so we return that value.

Attribution
Source : Link , Question Author : More Than Five , Answer Author : sfdcfox

Leave a Comment