Ruslan K · Jul 23, 2017

Check if class exists

There is method:

$System.OBJ.New( ClassName As  %String = "" )

If class with name ClassName exists - everything is OK.

But, when class does not exist, there is error - <CLASS DOES NOT EXIST>

How can I check before calling $System.OBJ.New() if class witn name ClassName exists?

2 0 19 2,676
Log in or sign up to continue

set exist=##class(%Dictionary.CompiledClass).%ExistsId(ClassName)

will tell you the status

Though it works, it's not literal: another programmer could ask himself why you tested the method %New, thus requiring to add a comment for explaining it. However if you use ExistsId, you're literally saying about testing if the class exists.

I know, it's just a detail, but still contributes for clean code directives.

so you may use $$$comClassDefined(class)  for compile classes

or go for ^oddCOM(....)

That's $$$defClassDefined(class). It shows that class definition exists (or doesn't), but it doesn't show if a class is compiled.

Luca, any reason for recommending %Exists and having to use $LISTBUILD when you could go direct to %ExistsId ?

Check if method %New exists with this function

$system.CLS.IsMthd(ClassName, "%New")

I'm fully with you.
Using hidden %System.whatever   Classes is as bad practice as using undocumented $zu(anynumber,  ,  , )

That is because the  CLS Package is used internally.
InterSystems uses it to verify if the method is defined or not without throwing exception.

This is probably faster than %ExistsId, because %ExistsId tries to open the instance beforehand instead.

I think it even works without any COS code, just like any other system functions. And they have more than just only IsMthd.

You're right, %Dictionary.CompiledClass actually overwrites the current %Persistent implementation for %Exists (which is called by %ExistsId).

@Eduard, where is the macro $$$comClassDefined defined?

%ExistsId does not open an object for %Dictionary package. Just checks the globals (see %Dictionary.CompiledClass for example).

The fastest way to check if a class exists would be:

write $$$comClassDefined(class)

And if you also want to be sure that also the Method %New exists you my use

write $$$comMemberDefined(ClassName,"m","%New")

[just reading through] uses such approach (in this case, for class %SYSTEM.CPU):

if $D(^oddDEF("%SYSTEM.CPU")) {

Use the official and documented API.

If pure existence or simply the class is defined (but not compiled)

SAMPLES>w ##class(%Dictionary.ClassDefinition).%Exists($lb("Aviation.Aircraft"))

If you're after existing and compiled:

SAMPLES>w ##class(%Dictionary.CompiledClass).%Exists($lb("Aviation.Aircraft"))



Pls. don't forget to mark your question as "answered" on Developer Community,
please click the checkmark alongside the answer you (as author of the question) accept