Ordinarily, when referencing a static class in a managed package from outside, we would do this:


Now, if the ns package is somehow uninstalled, this code should stop working, I assume. How would I be able to make sure that this code is executed only when the package is in the org?

Also, can I build the above code in an org in which the managed package does not exist?


Apex does not include full reflection capabilities so it is hard to do what you want. You can instantiate a class using e.g. Type.forName('...').newInstance() but there is then no way to invoke methods by name.

If you are willing to add quite a lot of code you can work-around the problem using techniques such as the one described in Breaking managed package dependencies. But that is quite painful.

  • Okay, so now that I know I have to hardcode it, the question is, will the build break if ns disappears? Or will it still compile? If ns isn't there, and I put an if check based on which that hardcoded function call is not executed in its absence, it shouldn't be an issue, or should it? – coldspeed Apr 18 '17 at 9:02
  • It would add a dependency if you add any code which refers to managed package – Raul Apr 18 '17 at 9:14
  • The platform compiles on demand so in general the compilation will fail if you have a reference to a namespace/class that is no longer present. But if you put the call in a class that you only instantiate via Type.forName when the namespace is present you can probably get it to work. – Keith C Apr 18 '17 at 9:35
  • Even if I instantiate it with Type.forName I'd have to cast it to the actual class type to call any method... this casting will raise an error in any case. – coldspeed Apr 18 '17 at 12:25
  • I'm suggesting making the call entirely in the Type.forName instantiated class, but that requires a lot of glue code. – Keith C Apr 18 '17 at 13:01

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.