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?
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(....)
I'm not having much success finding docs for $system.CLS
http://docs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=... says:
but no mention of CLS. Nor does the %SYSTEM package contain a CLS class in the same way as it contains the ones listed above.
That's $$$defClassDefined(class). It shows that class definition exists (or doesn't), but it doesn't show if a class is compiled.
as suggested earlier
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
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).
%occReference.inc
@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:
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 %occReference.inc]
mgstat.int 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)
If you're after existing and compiled:
--
HTH
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