1

I have a managed package with namespace myNamepace and a class ClassA which resides in that package will be dynamically instantiating objects of all subclasses of a particular abstract class SuperClass.

As of now, I assume the classes are in the same namespace and thus do:

// in ClassA
public SuperClass getInstance(String className) { 
    // classnName = 'ClassB' or 'ClassC', etc...
    return (SuperClass) Type.forName(className).newInstance();
}

However, if ClassB or ClassC, or any other subclass of SuperClass resided outside myNamespace, what would have to change? How would I then be able to figure out ClassB's namespace and then instantiate it? And what if ClassB does not have a namespace (for example, if it resides in a dev org), then can ClassA still instantiate it?

  • Edited question. – coldspeed Feb 16 '17 at 8:29
3

The documentation includes this comment about Type.forName(namespace, name):

Use this method instead of forName(fullyQualifiedName) if it will be called from a managed package installed in an organization with no defined namespace. To get the name of a local type, set the namespace argument to an empty string or null. For example, Type t = Type.forName('', 'ClassName');.

which covers the no-namespace case.

I've used code like this in a managed package to allow a class name to be set in a custom setting in the form "myNamepace.ClassA" or just "ClassA" for no namespace:

public static Type typeFor(String name) {
    Integer index = name.indexOf('.');
    if (index != -1) {
        // With namespace "ns.Type"
        return Type.forName(name.substring(index), name.substring(index + 1, name.length()));
    } else {
        // Just "Type"
        return Type.forName(null, name);
    }
}
| improve this answer | |
  • Can't believe I didn't see this. Thanks! – coldspeed Feb 16 '17 at 9:49
  • @Shiva It's an awkward API - I've shared your pain. – Keith C Feb 16 '17 at 9:50
  • Oh, got another question. If name is a class belonging to the same managed package, which is the best function to use? forName(null, class) or forName(class)? If you use one where you're supposed to use the other, is it going to spit exceptions at you or quietly flop? – coldspeed Feb 16 '17 at 9:53
  • 1
    @Shiva Definitely not forName(null, class); think the cleanest approach is to specify the namespace i.e. "yourpackagenamespace.YourClassName" rather than rely on that defaulting through one of the APIs. – Keith C Feb 16 '17 at 10:00

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.